What is a memory leak in C++ and how do you prevent it?
Updated 2026-07-10 · Beginner friendly
Quick answer
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.
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.
In the interview
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.
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