Pointers & Memory · advanced · ~8 min
Spot accesses after lifetime ends and move necessary reads before cleanup.
Use-after-free means accessing an allocation after its lifetime has ended. A run that appears to print the old value is still invalid; the result is not a reliable diagnostic. Learn the access order from the ownership contract before running code.
Copy any needed value before free. If traversing an owned structure later in the course, save the next link while the current node is alive, then free the current node.
An alias does not keep an allocation alive. Allocating a new object at a similar address does not make an old dangling pointer a valid reference to it.
The first exercise models whether a freed flag is set. The second validates a fuller lifecycle, including use-before-allocation and double-free. Neither executes an actual invalid memory access.
Use-after-free means accessing an allocation after its lifetime has ended. A run that appears to print the old value is still invalid; the result is not a reliable diagnostic. Learn the access order from the ownership contract before running code.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof *p);
if (p == NULL) return 1;
*p = 6;
int value = *p;
free(p);
printf("%d\n", value);
return 0;
}
Expected output on a successful allocation, where applicable:
6
Reading into value happens before the allocation is released. The final print reads the local copy. Moving the read below free would invalidate the program.
Object lifetime, not observed output, determines whether an access is valid. Read needed data before cleanup and stop using every alias after the owner releases storage.