If i have the following in a function:
struct example *A=malloc(sizeof(struct example));
does the node/memory space created where A points to get destroyed after the function ends/leaves? Or does it stay in the heap?
If i have the following in a function:
struct example *A=malloc(sizeof(struct example));
does the node/memory space created where A points to get destroyed after the function ends/leaves? Or does it stay in the heap?
You have to
free
everything that youmalloc
. When your function returns, the variableA
goes out of scope, but your memory stays allocated. As you have lost the pointer to the memory (unless stored elsewhere) you are leaking memory.If you still need the memory pointed to by
A
, you could return the pointer to the allocated struct, and free it later. If you don't need the allocated memory once your function returns, free the memory withfree(A)
.No. memory allocated by
malloc
will stay allocated untilfree
'd.Doing things like this:
on the other hand, is bad, because this object DOES go out of scope when the function ends.
malloc
allocates memory on the heap. Declaring variables allocates space on the stack. The stack is affected by scope, the heap is not.For additional information about the use of pointers, including various gotchas such as memory leaks (the process of losing a reference to
malloc
'd memory such that it persists forever), visit this link.