What Is a Memory Leak in C++?
Learn what causes a memory leak in C++, how smart pointers and RAII prevent it, and which tools detect leaks in real-world applications today.
Expected Interview Answer
A memory leak occurs when a program allocates heap memory (typically with `new` or `malloc`) but loses every reference to it without ever freeing it, so that memory stays reserved and unusable for the rest of the program's life even though nothing can access it anymore.
In C++, this most commonly happens when `new` is not matched by a corresponding `delete`, when an exception is thrown between an allocation and its planned cleanup (skipping the delete), or when a container of raw pointers is destroyed without explicitly deleting each pointed-to object first. Because C++ has no automatic garbage collector, the responsibility for freeing memory falls on the programmer or on RAII wrappers. The modern fix is to avoid raw owning pointers altogether: use `std::unique_ptr` for exclusive ownership and `std::shared_ptr` for shared ownership, both of which automatically call delete in their destructor, so memory is freed deterministically when the smart pointer goes out of scope — even if an exception unwinds the stack. Tools like Valgrind, AddressSanitizer, or built-in leak detectors help find leaks that slip through code review by tracking allocations that are never freed by program exit.
- Smart pointers (unique_ptr/shared_ptr) tie deallocation to scope automatically
- RAII ensures cleanup runs even when exceptions unwind the stack
- Sanitizer tools like Valgrind/ASan catch leaks missed by manual review
- Avoiding raw owning pointers eliminates an entire class of bugs
- Understanding leaks prevents long-running processes from exhausting memory
AI Mentor Explanation
A memory leak is like a groundstaff member checking out a piece of equipment from the store using a paper slip, then losing that slip before returning the item — the equipment sits somewhere on the ground forever, unreturnable, since nobody has the slip to reference it and check it back in.
Step-by-Step Explanation
Step 1
Allocation without matching deallocation
A `new` (or malloc) call that's never paired with `delete` (or free) is the root cause of most leaks.
Step 2
Losing the only pointer
Reassigning or letting the sole pointer to allocated memory go out of scope makes that memory unreachable and unfreeable.
Step 3
Exception paths skip cleanup
An exception thrown between allocation and a manual delete can bypass the cleanup code entirely, leaking memory.
Step 4
Adopt RAII / smart pointers
Wrap allocations in std::unique_ptr or std::shared_ptr so their destructor deletes automatically, even during stack unwinding.
Step 5
Detect leaks with tooling
Run Valgrind, AddressSanitizer, or a leak-detection build to catch allocations that were never freed.
What Interviewer Expects
- Defines a memory leak as unreachable, never-freed heap allocation
- Explains common causes: missing delete, lost pointers, exception paths
- Knows smart pointers (unique_ptr/shared_ptr) as the modern prevention strategy
- Understands RAII ties cleanup to object lifetime/scope
- Mentions at least one leak-detection tool (Valgrind, ASan, etc.)
Common Mistakes
- Confusing a memory leak with a dangling pointer (different problems)
- Believing C++ has automatic garbage collection like Java
- Manually pairing every new/delete instead of using RAII/smart pointers
- Forgetting that exceptions can skip manual cleanup code
Best Answer (HR Friendly)
“A memory leak happens when a program allocates memory and loses all references to it without ever freeing it, so that memory stays locked up and unusable — in modern C++ you prevent this by using smart pointers like unique_ptr and shared_ptr, which automatically free memory when they go out of scope.”
Code Example
void leaky() {
int* data = new int[1000];
if (someCondition()) {
return; // LEAK: never reaches delete below
}
delete[] data;
}
void safe() {
auto data = std::make_unique<int[]>(1000);
if (someCondition()) {
return; // OK: unique_ptr destructor frees memory automatically
}
} // freed here too, on normal exitFollow-up Questions
- What is the difference between a memory leak and a dangling pointer?
- How does std::shared_ptr's reference counting prevent premature deallocation?
- Can a shared_ptr cycle still cause a memory leak, and how do you fix it?
- How does RAII guarantee cleanup even when an exception is thrown?
- What tools would you use to diagnose a memory leak in a running C++ service?
MCQ Practice
1. What fundamentally causes a memory leak?
A leak occurs when heap memory is allocated but every reference to it is lost before it's freed.
2. Which C++ feature automatically frees memory even during exception unwinding?
Smart pointers tie deallocation to their destructor, which runs during stack unwinding, unlike manual delete calls.
3. What can still cause a leak even when using shared_ptr?
Two shared_ptrs referencing each other keep their reference counts above zero forever, leaking both objects.
Flash Cards
Memory leak — Heap memory allocated and never freed after all references are lost.
Common cause — Missing delete, lost pointer, or an exception skipping cleanup.
Modern prevention — Use std::unique_ptr/std::shared_ptr (RAII) instead of raw owning pointers.
Leak detection tools — Valgrind, AddressSanitizer, and similar sanitizer/profiler tools.