- 01What's happening
free() returns the heap block to malloc. The stack pointer arr is unchanged — it still holds the same address. Hence the name dangling pointer. You can still dereference arr, and the compiler won't complain.
- 02Why it doesn't crash right away
The freed block is still inside your process's address space — the OS hasn't taken it back. malloc just marked it as available. So you read stale values. Works sometimes. Breaks the moment malloc reuses the block for someone else and you read foreign data.
- 03Why C doesn't catch this
C asks the developer to track lifetimes. free() is just a regular function call — the compiler sees no link between free(arr) and a later arr[0]. Java/Python have garbage collection and bounds checking; in C, that's your job.
Right after every free(), set `arr = NULL;`. The next dereference then segfaults loudly — the bug surfaces instead of hiding. Failing fast beats silent corruption. In a large codebase this saves days of debugging.