Memory Leaks & Dangling Pointers
Memory leaks
A memory leak happens when memory is allocated on the heap but never freed, and the program loses every pointer that could have been used to free it. That memory stays reserved for the rest of the program's lifetime — useless, but unavailable for anything else. A single leak might be harmless, but leaks inside a loop or a long-running server can exhaust all available memory.
memory_leak.cpp
void leaky() {
int* data = new int[1000]; // allocate 1000 ints on the heap
// ... use data ...
// no delete[] before returning — this memory is now leaked!
} // 'data' (the pointer) is destroyed here,
// but the memory it pointed to is NOT freed
int main() {
for (int i = 0; i < 100000; i++) {
leaky(); // leaks a little more memory on every single call
}
return 0;
}Dangling pointers
A dangling pointer is the opposite problem: it points to memory that has already been freed. The pointer variable itself still holds the old address, but that address is no longer valid — the memory may have been returned to the system or reused for something else entirely. Dereferencing a dangling pointer is undefined behavior.
dangling_pointer.cpp
int* p = new int(42); delete p; // memory is freed — p is now dangling std::cout << *p << std::endl; // undefined behavior: reading freed memory *p = 10; // undefined behavior: writing to freed memory p = nullptr; // best practice: null out a pointer immediately after delete
Double-free bugs
double_free.cpp
int* p = new int(5); delete p; delete p; // undefined behavior: double free, often crashes or corrupts the heap
Detecting these bugs with tooling
Why this motivated modern C++
A memory leak: allocated memory that is never freed because every pointer to it is lost.
A dangling pointer: a pointer that still holds the address of memory that has already been freed.
A double free: calling delete twice on the same pointer, corrupting the heap.
Tools like Valgrind and AddressSanitizer help find these bugs, but the real fix is to avoid manual delete altogether.