Autocoder

C++ Memory Management Interview Questions

Last updated 2026-11-19

C++ gives you control over where objects live and when they die, and interviewers test whether you use that control safely. This page walks through stack and heap, leaks and double frees, allocation functions, placement new, alignment and the habits that make most manual management unnecessary.

The strong answer is nearly always the same shape: say what the raw mechanism does, point out how it fails, and then say what you would use instead, usually a container or a smart pointer. Related reading: C++ smart pointers questions, C++ pointers and references and the operating-system view in OS memory management.

TopicsStack, heap, new/delete, leaks, alignment
ToolsAddressSanitizer, Valgrind
StandardC++17

Storage durations to know

Tools that find the bugs

Compile with -fsanitize=address,undefined and run the tests. AddressSanitizer reports heap overflows, use-after-free and leaks with the allocating stack trace. Valgrind memcheck does a similar job without recompiling. Mentioning that you have used one of these is worth more than a memorised definition of a leak.

C++ Memory Management Interview Questions: questions with worked answers

  1. 1

    What is the difference between stack and heap allocation?

    easy

    Stack memory holds automatic variables and is managed by moving the stack pointer: allocation is nearly free, lifetime ends at scope exit, and size is small (commonly 1 to 8 MB per thread), so deep recursion or a huge local array overflows it. Heap memory is obtained at run time with new or malloc, lives until you free it, can be large and is slower because the allocator must find and track blocks. Heap blocks can fragment and need a deliberate owner.

  2. 2

    What is a memory leak? Give an example that is not obvious.

    easy

    A leak is dynamically allocated memory that is no longer reachable and never freed. Obvious: forgetting delete. Less obvious: an exception thrown between new and delete, an early return, or a constructor that throws after allocating a member. In the snippet, if g() throws, the allocated buffer leaks because delete is never reached. unique_ptr or a vector fixes every variant.

    cpp
    void f() {
        int* p = new int[100];
        g();            // may throw
        delete[] p;     // skipped on exception
    }
    void f_ok() {
        std::vector<int> v(100);
        g();            // v freed automatically
    }
  3. 3

    What is a double free and how does it happen?

    medium

    Freeing the same block twice corrupts the allocator's bookkeeping and is undefined behaviour: it can crash immediately, crash later in unrelated code, or become exploitable. It arises from shallow copies of a class owning a raw pointer (both destructors delete), two owners of one pointer, or freeing a pointer and then freeing an alias. Fixes: a single clear owner (unique_ptr), deleting copy operations, or deep copy. Setting a pointer to nullptr after delete protects only that pointer, not its copies.

  4. 4

    What does operator new do beyond malloc, and what is a new-expression?

    medium

    The new-expression does two steps: it calls the allocation function operator new(size) to obtain raw storage, then runs the constructor in that storage. If the constructor throws, the storage is released automatically. operator new can be overloaded globally or per class to customise allocation, for example for pools. Failure throws std::bad_alloc, or returns nullptr with new(std::nothrow). The delete-expression similarly runs the destructor, then calls operator delete.

  5. 5

    What is placement new and when is it used?

    hard

    Placement new constructs an object at an address you supply, without allocating: new (ptr) T(args). It is used inside containers, pools, arenas and embedded code that manage raw storage. You must ensure the storage is large enough and correctly aligned, and you must destroy the object manually by calling its destructor, then release the storage separately. std::vector uses it internally, and C++20 std::construct_at is a cleaner spelling.

    cpp
    alignas(std::string) unsigned char buf[sizeof(std::string)];
    std::string* s = new (buf) std::string("hello");
    std::cout << *s;
    s->~basic_string();   // manual destruction, no delete
  6. 6

    What is memory alignment and why does sizeof sometimes include padding?

    medium

    Each type has an alignment requirement (often equal to its size for fundamental types), and the compiler inserts padding so every member sits at a properly aligned offset and arrays of the struct stay aligned. Ordering members from largest to smallest usually shrinks the struct. The size is rounded up to a multiple of the largest member alignment.

    cpp
    struct A { char c; int i; char d; };   // 12 on typical platforms
    struct B { int i; char c; char d; };   // 8
    static_assert(sizeof(B) == 8);
  7. 7

    Explain deep copy versus shallow copy.

    medium

    A shallow copy duplicates the pointer value, so both objects share one heap block, and changes show through both and the block is freed twice. A deep copy allocates a new block and copies the contents so the objects are independent. The compiler-generated copy is shallow for raw pointers. Implement the copy constructor and assignment, or use members that deep-copy themselves, like std::vector and std::string.

  8. 8

    What is the difference between malloc/free, new/delete and new[]/delete[]?

    medium

    malloc returns uninitialised raw bytes as void*, never runs constructors and returns NULL on failure; free pairs with it. new allocates and constructs one object; delete destroys and frees. new[] allocates and constructs an array and records the element count somewhere; delete[] destroys each element in reverse order and frees. Each allocation must be released with its matching form, and mismatches are undefined behaviour. realloc cannot be used on objects with non-trivial constructors.

  9. 9

    What are the benefits of std::vector over a raw dynamic array?

    medium

    It owns its memory (RAII), knows its size, grows automatically, copies deeply, moves cheaply (just swaps three pointers), works with algorithms and range-for, and offers bounds-checked access with at(). It is also contiguous, so passing v.data() and v.size() to C APIs is fine. A raw new[] gives none of this and needs manual delete[]. The only time to prefer a raw array is fixed small sizes, where std::array avoids the heap.

  10. 10

    How does move semantics reduce allocations? Show a move constructor.

    hard

    A move constructor takes over the source object's resources by copying pointers and leaving the source in an empty, destructible state, so no allocation or element-wise copy is needed. It should be noexcept: std::vector uses move_if_noexcept on reallocation, so a throwing move constructor makes it fall back to copying.

    cpp
    struct Buf {
        int* p; size_t n;
        Buf(Buf&& o) noexcept : p(o.p), n(o.n) { o.p = nullptr; o.n = 0; }
        Buf& operator=(Buf&& o) noexcept {
            if (this != &o) { delete[] p; p = o.p; n = o.n; o.p = nullptr; o.n = 0; }
            return *this;
        }
        ~Buf() { delete[] p; }
    };
  11. 11

    What is a stack overflow and how can it happen in C++?

    medium

    The call stack exceeds its fixed size. Typical causes are unbounded or very deep recursion (a recursion depth of a few hundred thousand frames with moderate frame sizes) and very large local arrays such as int a[10000000]. The fix is an iterative algorithm with an explicit stack, moving large buffers to the heap with std::vector, or increasing the stack limit as a stopgap. Tail recursion is not guaranteed to be optimised in C++.

  12. 12

    What is a memory arena or pool allocator, and why use one?

    hard

    An arena allocates a large block once and hands out pieces by bumping a pointer, freeing everything at once at the end; a pool recycles fixed-size slots. Both avoid per-object malloc cost, reduce fragmentation and improve cache locality, which suits parsers, games and short-lived request data. In standard C++ you can plug one in through std::pmr::monotonic_buffer_resource and std::pmr containers (C++17) without writing your own allocator type.

  13. 13

    How would you detect memory errors in a C++ program?

    medium

    Build with AddressSanitizer (-fsanitize=address) to catch heap and stack overflows, use-after-free and leaks, UndefinedBehaviorSanitizer for overflow and alignment issues, and ThreadSanitizer for data races (it cannot be combined with ASan). Valgrind memcheck works on an unmodified binary but is slower. Add static analysis such as clang-tidy and compiler warnings. Say that tools prove the presence of bugs, not their absence, so design with RAII so that the class of bug cannot occur.

  14. 14

    What does "Rule of RAII: no naked new" mean?

    easy

    Application code should not contain a raw new whose result is stored in a plain pointer. Allocation results go straight into a smart pointer or container (make_unique, make_shared, vector), so that ownership is encoded in the type and release is automatic on every path. Raw new belongs inside resource-managing classes and low-level libraries only.

Frequently asked questions

Does C++ have garbage collection?

No. Memory is released by destructors and explicit delete, so RAII and smart pointers play the role that garbage collection plays in Java.

Why is delete[] needed for arrays?

Because the compiler must call each element destructor and know the block size. Using plain delete on new[] is undefined behaviour.

Is it ever fine to use malloc in C++?

For trivially constructible data in code interoperating with C, yes. For anything with a constructor, use new or containers.

How is this different from the C version of the topic?

C has only malloc and free, no constructors and no RAII. See C language questions for that view.

Related guides

More in Programming Language Interview Questions by Language

See all in this section