Certainly allocating and freeing the same pointer is well defined ...
void *p1 = malloc(42);
void *p2 = malloc(42);
uintptr_t u2 = (uintptr_t) p2;
void *p3 = (void *) u2;
// Specified to evaluate true C11 126.96.36.199
if (p2 == p3) ...
// Maybe true, maybe false
if (memset(&p2, &p3, sizeof p2) == 0) ...
Thefunction causes the space pointed to by
freeto be deallocated, ... if the argument does not match a pointer earlier returned by a memory management function ... behavior is undefined. C11dr §188.8.131.52 3
void *p4 = malloc(42);
uintptr_t u4 = (uintptr_t) p4;
void *p5 = (void *) u4;
free(p5); // UB or not UB?
References are to N1570, the latest publicly available draft of the 2011 ISO C standard (C11).
void *p4 = malloc(42); assert(p4); uintptr_t u4 = (uintptr_t) p4; ... void *p5 = (void *) u4; ... free(p5); // UB or not UB?
The definition of
uintptr_t guarantees that the pointer values
p5 compare equal; more tersely,
p4 == p5. From the definition of
== for pointers in 6.5.9p6, we know that
p5 point to the same object (since we've already established that the value of
p3 is not a null pointer).
This doesn't guarantee that they have the same representation. The standard says very little about the representation of pointers (except that they have a representation), so it's entirely possible that
p5 have different representations. The standard explicitly permits this in 184.108.40.206p4:
Two values (other than NaNs) with the same object representation compare equal, but values that compare equal may have different object representations.
(That may or may not actually be possible, depending on the implementation.)
Now the question is, what exactly is passed to
Function calls are described in 220.127.116.11. Paragraph 4 says:
In preparing for the call to a function, the arguments are evaluated, and each parameter is assigned the value of the corresponding argument.
free() sees is not the object representation of
p5 (which might differ from the object representation of
p4), but the value of
p5, which is guaranteed to be the same as the value of
p4. It's likely that the mechanism by which that value is passed might involve making a copy of the object representation, but all the standard says is that the value is passed, and
free must treat any distinct representations of the same value in the same way.