Lesson 24: Memory safety — leaks & dangling pointers
We've learned to request memory — now we learn not to get burned by it. A memory leak happens when you lose the last pointer to a block without freeing it, e.g. by assigning a new address to p before free. A double free is undefined behavior, and using a pointer after free — a dangling pointer — is
Think of storage-unit keys: a leak is losing the only key to a full unit — the unit is occupied forever. A double free is trying to return the same key twice — the front desk freaks out. A dangling pointer is using a copy of a key to a unit you already returned — who knows what (or who) is in there now.
- memory leak
- Losing the last pointer to an allocated block without calling free — the memory stays occupied with no way to release it.
- double free
- Calling free twice on the same block. Undefined behavior — a crash or memory corruption.
- dangling pointer
- A pointer that still holds the address of a freed block. Using it (use-after-free) is undefined behavior.
- ownership
- The defensive mindset: every block has one 'owner' responsible for freeing it — exactly once. Always ask 'who is responsible for freeing this?'.
- valgrind
- A tool that runs your program and detects leaks and memory errors: valgrind ./prog.