C Language Undefined behavior Read value of pointer that was freed

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Even just reading the value of a pointer that was freed (i.e. without trying to dereference the pointer) is undefined behavior(UB), e.g.

char *p = malloc(5);
free(p);
if (p == NULL) /* NOTE: even without dereferencing, this may have UB */
{

}

Quoting ISO/IEC 9899:2011, section 6.2.4 §2:

[…] The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

The use of indeterminate memory for anything, including apparently harmless comparison or arithmetic, can have undefined behavior if the value can be a trap representation for the type.



Got any C Language Question?