Skip to main content
gamedev.net
🔒 Locked

Simple memory allocations question

Started by CRACK123 Mar 11, 2005 at 10:47 AM 1 replies 650+ views
Original Post
CRACK123
CRACK123
Hi, Lets say I have some code like this :-
[Source]
struct A
{
   ....
};

A *Function()
{
    A *a = new A;
    ....
    ....
    return a;
}
[/Source]
And Lets say I do the following :- A *a = Function(); Now I am allocation information to a local variable so would the content be lost once the function exits ? How exactly does this work considering "a" is just pointing to the information in "local structure "a" ." Just trying to understand how it works under the hood. Thanks
The more applications I write, more I find out how less I know
cozman
cozman
You are returning the pointer, you can do something like:
A* foo = Function();  // get a pointer to the new A created in Functionfoo->bar();  // use foo (assuming bar() is a member of A*)delete foo;  // necessary, since foo isn't being deleted where it is created (in Function)


In practice it's often a good idea to not return bare pointers, as the person calling the function might not know if it is their duty to delete it, nor whether it should be deleted with 'delete' or with 'delete[]. std::auto_ptr and boost::shared_ptr are good solutions to this problem for normal pointers, to pointers adressing blocks of memory (dynamic arrays) it is best to use an STL container like std::deque or std::vector.
kdogg
kdogg
Your A struct is allocated on the heap in Function(). Therefore, it will not be deleted when the function returns. The calling function will be able to use the newly allocated structure as if it had allocated the struct itself. The calling function will have to delete the variable or else the program will have a memory leak.

The problem arises when you try to return a local variable. These are allocated on the stack and will go out of scope (be destroyed) when the function returns. If your function looked like:

A *Function(){    A a;    ....    ....    return &a}

You're most likely headed towards a seg fault as the memory where 'a' resides is now free for anyone to use. You could get around this by declaring 'a' as a static variable. In that case, its place on the stack is reserved and therefore won't be subject to removal when the function returns (I'm not saying that it's a good idea to do that, this is just a proof of concept).

The general rule of thumb is that you can pass pointers to local variables up the stack, but not down it. That is, passing a pointer to a local variable to a function is legal, but returning it will usually cause problems unless you really know what you are doing.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.