What is a memory leak in C++ and how do you prevent it?
A memory leak happens when you allocate memory with new but never free it, so that memory stays reserved and unavailable until the program ends. Over time leaks make a program use more and more memory. You prevent them by pairing every new with a delete, or better, by using smart pointers and RAII so cleanup is automatic.
- A memory leak is memory allocated with new that is never freed, so it stays reserved.
- Leaks build up over time and can eventually exhaust available memory.
- Prevent them with smart pointers and RAII so cleanup happens automatically.
How a leak happens
void leak() {
int* p = new int(5);
// forgot delete p; -> memory leaked
}
How to prevent leaks
- Pair every new with a delete on all code paths.
- Use smart pointers so memory frees itself.
- Follow RAII, tying resource lifetime to object scope.
- Use tools like Valgrind or sanitizers to detect leaks.
Do not stop at pairing new and delete. Say the reliable fix is smart pointers and RAII, because manual delete is easy to miss on early returns or exceptions. That framing shows you think about real code, not toy examples.
Frequently asked questions
How does RAII prevent leaks?
RAII ties a resource to an object's lifetime, so when the object goes out of scope its destructor releases the resource automatically, even on exceptions.
What tools detect memory leaks?
Tools like Valgrind and the AddressSanitizer detect leaks and invalid memory use by tracking allocations that are never freed.
Common follow up questions
Related interview questions
Want the full C++ guide?
Read every C++ concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the C++ guide All C++ questions