scope of struct pointers in functions

2019-08-12 08:28发布

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?

2条回答
SAY GOODBYE
2楼-- · 2019-08-12 09:07

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).

查看更多
Root(大扎)
3楼-- · 2019-08-12 09:23

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.

查看更多
登录 后发表回答