scope of struct pointers in functions

不问归期 提交于 2020-01-05 19:12:21

问题


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



来源:https://stackoverflow.com/questions/15537890/scope-of-struct-pointers-in-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!