2

Assume I dynamically allocate memory by creating the pointer p1:

int *p1 = malloc(10*sizeof(int));

Then I create a second pointer (p2) and make it point to the same block of memory:

int* p2; 
p2 = p1;

Then I want to return the memory block back to the heap, so I give the following command:

free(p1);

My question is this: is the block of memory actually free now or is it still occupied because p2 is still pointing to it (i.e. blocking it)?

steady_progress
  • 3,311
  • 10
  • 31
  • 62
  • 2
    C does not employ *reference counts* like some languages do, so if you `free` memory it can be reused, regardless of how many pointers are pointing at it. That makes C much faster than other languages - and more dangerous as well. – cdarke Dec 17 '16 at 13:58

2 Answers2

4

My question is this: is the block of memory actually free now or is it still occupied because p2 is still pointing to it (i.e. blocking it)?

No, it has been freed.

Moreover you should be careful in such cases to not delete the memory twice (e.g. first via p1 then via p2) - otherwise you will trigger undefined behavior.

Actually this is also useful (C11):

The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

And using indeterminate memory is a bad idea. So after freeing the memory even stuff like this is a bad idea:

free(p1);
if(p2 == NULL) // oops. don't do this
  doSmth();

Some more details are in this answer.

Community
  • 1
  • 1
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
2

Once it's freed it's freed.

What you have left is a dangling pointer which you can no longer de-reference, or do anything with in fact.

doctorlove
  • 18,872
  • 2
  • 46
  • 62