2
3
4
5
0x7ffd98a0
0x00501000
🤔 Socratic Invariant Discovery
Don't look at the solution immediately! Step through these 3 guided questions to understand why this bug occurs so you'll never make it again on an exam.
The Airbnb Key After Checkout
Imagine renting an Airbnb for the weekend. On Monday morning, you checkout and the host cleans the room. However, you secretly made a copy of the front door key. On Tuesday night, you try to unlock the apartment door with your old key and walk in to sleep on the bed.
In C, free(ptr) returns ownership of the memory back to the operating system, but the variable ptr still holds the old address! Dereferencing a freed pointer is like trespassing with an old key — it may crash immediately (segfault), or worse, silently corrupt whatever data now lives there.
🛡️ Defensive Code Patch & Best Practice
Compare the vulnerable code against the memory-safe implementation:
Rule of Thumb Checklist to Avoid This:
- Always check if pointer is non-NULL before dereferencing:
if (ptr != NULL) - Immediately set pointer to NULL after freeing:
free(ptr); ptr = NULL; - Pair every
malloc()with an explicitfree()along every return path.