Reputation: 99
My professor showed the following code:
void *p1=malloc(1024);
free(p1);
void *p2=malloc(1024);
if (p1==p2)
{
printf("Now What?")
}
and he said it's unsafe, but why?
I know we shouldn't try access memory which was freed. However, it's OK to know where the pointer is pointing since it's just a normal pointer, as long as we don't try to read from where it's pointing to.
Upvotes: 4
Views: 217
Reputation: 211
The above code behavior will be undefined because the pointed object is destroyed by the free function. The standard already mentioned it in their draft.
"If a pointer value is used in an evaluation after the object the pointer points to (or just past) reaches the end of its lifetime, the behavior is undefined."
They also describe that the representation of a pointer object becomes indeterminate when the object the pointer points to (or just past) reaches the end of its lifetime".
Upvotes: 0
Reputation: 223872
This is in fact unsafe because a pointer to freed memory is indeterminate.
Annex J.2 of the C standard, which gives examples of undefined behavior, includes the following:
- The value of a pointer to an object whose lifetime has ended is used (6.2.4).
...
- The value of a pointer that refers to space deallocated by a call to the
free
orrealloc
function is used (7.22.3).
Where section 7.22.3p1 regarding memory management functions states:
... The lifetime of an allocated object extends from the allocation until the deallocation ...
And section 6.2.4p2 which defines the lifetime of an object states:
The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
Upvotes: 3