int main()
{
int* Pointer;
Pointer = (int*) malloc(sizeof(int));
*Pointer = 33;
int* Pointer2 = Pointer;
printf("%d\n", *Pointer);
free(Pointer);
free(Pointer2);
return 0;
}
The output is 33 with no errors or warnings.
I declared two pointers that are pointing to the same heap address.
I know it's wrong to free them both and it is sufficient to only free one. Is it undefined if I free them both and will it do anything wrong if I free the same heap area from different pointers (Pointer
and Pointer2
)?
As per the C11 standard draft 7.22.3.3p2
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. If ptr is anull
pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined.
(The emphasis is mine..)