Ammar S
Ammar S

Reputation: 61

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?

Upvotes: 0

Views: 147

Answers (4)

haccks
haccks

Reputation: 105992

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.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227370

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.

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 612794

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

Upvotes: 1

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

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.

Upvotes: 0

Related Questions