Memory leaks, dangling pointers and double free

Difficulty: Intermediate

Question

What is a memory leak? What is a dangling pointer? How do you detect and prevent these bugs in C++?

Answer

These two bugs are the reason C++ has a reputation for being dangerous, and also the reason modern C++ has so many tools to avoid them. An interviewer asking this wants to hear not just definitions but a prevention strategy.

A memory leak happens when you allocate heap memory and lose every pointer to it before freeing it. The memory is still marked as used, but nobody can ever release it. Think of renting lockers at a railway station and throwing away all the keys: the lockers stay occupied forever. In a short program it is harmless, because the OS reclaims everything at exit, but in a long-running server or an embedded device it slowly eats memory until the process dies. Typical causes: forgetting delete, returning early or throwing an exception between new and delete, overwriting a pointer that held the only reference, and circular shared_ptr references.

A dangling pointer is the opposite problem: the pointer still holds an address, but the object at that address is gone. Imagine a friend's old address on a card after they have moved out; a stranger may live there now. Common sources: using a pointer after delete, returning the address of a local variable, keeping a pointer or iterator into a vector that has reallocated, and holding a reference to a temporary. Dereferencing a dangling pointer is undefined behaviour; it may crash, print garbage, or appear to work today and fail in production tomorrow. A related bug is the double free, calling delete twice on the same address, which usually corrupts the allocator's bookkeeping.

How do you find them? Use tools: Valgrind (memcheck) and AddressSanitizer (compile with -fsanitize=address) catch leaks, use-after-free and double frees; LeakSanitizer reports leaks at exit; Visual Studio has CRT debug heap checks. Static analysers such as clang-tidy and cppcheck catch many patterns before you even run the code.

How do you prevent them? First, follow RAII: let an object own the memory so that its destructor frees it. In practice that means containers (vector, string) and smart pointers (unique_ptr for sole ownership, shared_ptr for shared ownership, weak_ptr to break cycles) instead of raw new and delete. Second, set a raw pointer to nullptr after deleting it if you must use one, since deleting nullptr is a no-op and dereferencing it fails loudly instead of silently. Third, never return references or pointers to locals. Fourth, follow the rule of three/five so that copies do not accidentally share ownership.

Interviewers often ask about exceptions specifically: 'int* p = new int[100]; mayThrow(); delete[] p;' leaks if mayThrow throws. The fix is a unique_ptr<int[]> or a vector, whose destructors run during stack unwinding.

One final nuance: a leak is 'lost memory', while a dangling pointer is 'lost validity'. They are different failure modes, and a good answer names both and pairs them with RAII as the single unifying cure.

Code examples

Leak, dangling pointer and their fixes

#include <iostream>
#include <memory>
#include <stdexcept>
#include <vector>

void mayThrow() { throw std::runtime_error("boom"); }

void leaky() {
    int* p = new int[100];
    mayThrow();          // exception: delete[] below never runs -> leak
    delete[] p;
}

void safe() {
    auto p = std::make_unique<int[]>(100);
    mayThrow();          // unique_ptr destructor frees during unwinding
}

int main() {
    try { safe(); } catch (const std::exception& e) { std::cout << "caught " << e.what() << "\n"; }

    int* q = new int(5);
    delete q;
    q = nullptr;                     // avoid a dangling pointer
    std::cout << (q == nullptr ? "null" : "valid") << "\n";

    std::vector<int> v{1, 2, 3};
    int* first = &v[0];
    v.push_back(4);                  // may reallocate: 'first' may now dangle
    first = &v[0];                   // re-acquire after modification
    std::cout << *first << "\n";
    (void)leaky;
}

safe() cleans up automatically even when an exception is thrown. leaky() is included only to show the pattern and is never called.

Key points

Common follow-up questions

Interview tips

Concepts covered

memory leak, dangling pointer, double free, valgrind

More C++ & STL questions