Returning a Block Of Resources

closed account (zb0S216C)
I'm unsure about returning memory allocated by a local object within a function, such as malloc( ). I was thinking something along the lines of: If I allocate a block of resources with a local object within a function and return it, will that be safe?

To illustrate my point, consider this code:

1
2
3
4
5
6
7
8
9
int *NewBlock( const int Blocks )
{
    int *MemBlock( new( std::nothrow ) int[ Blocks ] );

    if( !MemBlock )
        return NULL;

    return MemBlock;
}

Since MemBlock is local to NewBlock( ), once NewBlock( ) finishes, MemBlock is popped from the stack. So, where does the memory go? who's the owner of this memory?

I hope you understand what I'm saying here :)

Wazzak
So, where does the memory go?

It's not going anywhere. Memory allocated by new[] is not freed until you call delete[].
... and presumably at the other end of the call to your function you save the address of that block of memory somewhere...

1
2
3
int *blocks = NewBlock( 12 );
...
delete [] blocks;

Hope this helps.
closed account (zb0S216C)
@Duoas: So basically, I'm passing ownership of the memory allocated by MemBlock to the pointer that called NewBlock( ) (like your example)?

Wazzak
Exactly.
closed account (zb0S216C)
Thanks, Duoas :)

Wazzak
Topic archived. No new replies allowed.