malloc and free in C

Deadly 提交于 2019-12-13 06:51:11

问题


if I have something like

 struct Node *root;
 struct Node *q;

 root = malloc( sizeof(struct Node));
 q = root;
 free(q);

is the node q is pointing to freed?? or would I have to pass root to the free function?


回答1:


Both root and q have the same value, that is to say, they point to the same memory location. After the call to free(q), both of them are dangling pointers because the thing they both point to has been freed but they still point to that location.

To de-reference either would invoke undefined behaviour. This includes calling free on either of them.




回答2:


The pointers q and root point to the same block of memory after the assignment. So the call to free will free that block and both q and root are left dangling.

You can write

free(q);

or

free(root);

interchangeably since

q == root



回答3:


After calling free(q) the freed memory is not being cleared or erased in any manner.
Both q and root are still pointing to the allocated memory location but that memory location is added to the list of free memory chunks and can be re-allocated. You are not allowed to reference that memory location by any of these pointers otherwise it will invoke undefined behavior.




回答4:


After free call both q and root point to freed memory block.

Generally, each resource has to be released only once. This is different from C++, where you can implement (but probably should not) pretty complex logic of resource management.



来源:https://stackoverflow.com/questions/28643691/malloc-and-free-in-c

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