0

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?

Ammar S
  • 91
  • 8
  • 1
    Please note that `malloc` and `free` operate on *memory zones*, not on variables. You may have several variables holding the *same* pointer. Read about [pointer aliasing](http://en.wikipedia.org/wiki/Pointer_aliasing) – Basile Starynkevitch Feb 21 '15 at 08:25
  • I know about pointer aliasing, just not sure how free works – Ammar S Feb 21 '15 at 08:40
  • saying that free works on memory zones cleared it up though. thanx – Ammar S Feb 21 '15 at 08:46

4 Answers4

3

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

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.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • 1
    In some implementations (and notably for large memory blocks), `free` might sometimes release memory by giving it back to the operating system (e.g. with `munmap` on Linux or POSIX). But usually `free` simply makes the memory zone reusable for future `malloc` – Basile Starynkevitch Feb 21 '15 at 08:45
1

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
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

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.

Valeri Atamaniouk
  • 5,125
  • 2
  • 16
  • 18