C++ Interview Question

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

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.

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