Based on my understanding, the comparison of a == b
itself would be UB..
Well, yes.
Regarding the "why" part, as mentioned in haccks's answer, after a pointer has been free()
d, the object it points to reaches the end of it's lifetime, thus making the pointer value indeterminate. So, any further use (read) of the pointer itself would be unspecified behavior at best and any attempted usage of the address pointed to by it, would invoke undefined behavior.
So, technically, the optimization you expect, would be correct and would be a must to make the code exhibit a defined behavior, as the code is incorrect to start with. Do not expect the compiler to correct your code, it may not.
That said, regarding
Can we safely say that "b" does not alias with "a"?
I'm not very clear on what ground you used the alias here, but just to be sure, the official wording, from C11
, chapter §7.22.3.5,
P2:
The realloc
function deallocates the old object pointed to by ptr
and returns a
pointer to a new object that has the size specified by size
. The contents of the new
object shall be the same as that of the old object prior to deallocation, up to the lesser of
the new and old sizes. [...]
P3:
[...] If ptr
is a null pointer, the realloc
function behaves like the malloc
function for the
specified size
. Otherwise, if ptr
does not match a pointer earlier returned by a memory
management function, or if the space has been deallocated by a call to the free
or
realloc
function, the behavior is undefined. If memory for the new object cannot be
allocated, the old object is not deallocated and its value is unchanged.
and, P4:
The realloc
function returns a pointer to the new object (which may have the same
value as a pointer to the old object), or a null pointer if the new object could not be
allocated.