The value of p
cannot be used as such after the memory it points to has been freed. More generally, the value of an uninitialized pointer has the same status: even just reading it for the purpose of copying to invokes undefined behavior.
The reason for this surprising restriction is the possibility of trap representations. Freeing the memory pointed to by p
can make its value become a trap representation.
I remember one such target, back in the early 1990s that behaved this way. Not en embedded target then and rather in widespread use then: Windows 2.x. It used the Intel architecture in 16-bit protected mode, where pointers were 32-bit wide, with a 16-bit selector and a 16-bit offset. In order to access the memory, pointers were loaded in a pair of registers (a segment register and an address register) with a specific instruction:
LES BX,[BP+4] ; load pointer into ES:BX
Loading the selector part of the pointer value into a segment register had the side effect of validating the selector value: if the selector did not point to a valid memory segment, an exception would be fired.
Compiling the innocent looking statement q = p;
could be compiled in many different ways:
MOV AX,[BP+4] ; loading via DX:AX registers: no side effects
MOV DX,[BP+6]
MOV [BP-6],AX
MOV [BP-4],DX
or
LES BX,[BP+4] ; loading via ES:BX registers: side effects
MOV [BP-6],BX
MOV [BP-4],ES
The second option has 2 advantages:
The code is more compact, 1 less instruction
The pointer value is loaded into registers that can be used directly to dereference the memory, which can result in fewer instructions generated for subsequent statements.
Freeing the memory may unmap the segment and make the selector invalid. The value becomes a trap value and loading it into ES:BX
fires an exception, also called trap on some architectures.
Not all compilers would use the LES
instruction for just copying pointer values because it was slower, but some did when instructed to generate compact code, a common choice then as memory was rather expensive and scarce.
The C Standard allows for this and describes a form of undefined behavior the code where:
The value of a pointer to an object whose lifetime has ended is used (6.2.4).
because this value has become indeterminate as defined this way:
3.19.2 indeterminate value: either an unspecified value or a trap representation
Note however that you can still manipulate the value by aliasing via a character type:
/* dumping the value of the free'd pointer */
unsigned char *pc = (unsigned char*)&p;
size_t i;
for (i = 0; i < sizeof(p); i++)
printf("%02X", pc[i]); /* no problem here */
/* copying the value of the free'd pointer */
memcpy(&q, &p, sizeof(p)); /* no problem either */
p
is a local variable on the stack, but it points to the heap. And if you dereferenceq
after your code snippet, you have undefined behavior.unsigned int
when writing C code. And evenunsigned
can be mis-used.