scope of struct pointers in functions

2019-08-12 08:25发布

问题:

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?

回答1:

No. memory allocated by malloc will stay allocated until free'd.

Doing things like this:

char * function(void)
{
    char c = 'a';
    return &c;
}

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.



回答2:

You have to free everything that you malloc. When your function returns, the variable A 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 with free(A).