简体   繁体   中英

malloc and free in C

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?

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM