Reputation: 785
Couldn't seem to find an answer to my question elsewhere.
Consider the code:
int *ptr = malloc (sizeof (*ptr));
int *dummyPtr = ptr;
free (dummyPtr);
printf ("ptr: %p, dummy: %p\n", ptr, dummyPtr);
As I understand it, free()
takes in a pointer and makes it point to NULL
aka (nil)
. I.e., the pointer is dereferenced and points nowhere. This means that the memory pointed to by the pointer is effectively erased.
Two parts to this question:
dummyPtr
still seems to point to an address in memory and not (nil)
. Why?ptr
? Will it still point to that block of memory or has it been dereferenced too?I've run this code and some variants a few times with conflicting results. Sometimes only the copy is affected, sometimes both. Sometimes the values pointed to are even set to zero!
Frankly, I have no idea what's going on. (I'm running Debian, if that makes a difference.)
Upvotes: 1
Views: 2261
Reputation: 141618
free
does not set the pointer to NULL , or erase any memory. Instead, it marks the memory block that the pointer is pointing to as being free (i.e. not allocated).
After the call to free(dummyPtr)
, both ptr
and dummyPtr
are now invalid pointers, because they do not point to an allocated block of memory.
Your printf
line causes undefined behaviour by using an invalid pointer. When undefined behaviour has happened, all bets are off.
Standard references: C11 6.2.4/2
The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
Annex J.2:
The behavior is undefined in the following circumstances:
- The value of an object with automatic storage duration is used while it is indeterminate
Upvotes: 5
Reputation: 36092
To understand look at the prototype for free()
void free(void *ptr)
It is not possible for the function to change ptr to point to NULL even if it wanted that, ptr is just copied to the function so it can only free what ptr points to.
In order for a free to change that it would need a prototype like
void free(void **ptr)
Once free has been called on the pointer using the memory that ptr pointed to is undefined behavior since the memory has been returned to the OS.
Upvotes: 1
Reputation: 565
Dummyptr still holds the old memory location. After the free both prt and dummyptr become spent and should not be dereferenced as this will result in undefined behaviour.
Upvotes: 1
Reputation: 84569
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
Where do you get that free
sets the pointer to NULL
-- it doesn't. That is your job if you want to reuse the pointer. If you are not reusing it, then is makes no difference where it points.
Upvotes: 2