skip to content

New and Delete

new allocates and constructs, delete destroys and frees, and the array forms must match. Interviewers probe placement new, mismatched delete and what operator new can be replaced with.

on this pageshow

explore

questions

5

In C++, why must memory from new[] be released with delete[] rather than delete?

level: juniorimportance: must knowfreq 70%

answer

  1. how many destructors to run
  2. the element count is hidden
  3. array cookie before the elements
  4. mismatch is undefined behaviour

basics

~10 s

delete[] runs the destructor of every element and calls the array deallocation function; plain delete destroys one object and calls the single-object one. Mixing them is undefined behaviour, often a crash or silent leak.

solid answer

~40 s

A `new T[n]` expression allocates through `operator new[]` and constructs `n` objects; the matching `delete[] p` must destroy all `n` in reverse order and free through `operator delete[]`. To know `n`, implementations commonly store an **array cookie** in front of the elements when `T` has a non-trivial destructor - with Apple clang on arm64 the block for four 32-byte `Particle`s is 144 bytes and the pointer you get is 16 bytes in. Plain `delete p` on that pointer destroys at most one element and hands the wrong address to the wrong deallocation function: undefined behaviour, which here aborts with AddressSanitizer's `bad-free`. For trivially destructible types it often "works", which is why it survives review. Clang warns with `-Wmismatched-new-delete` when it can see both sides; `std::vector` or `std::unique_ptr<T[]>` removes the choice entirely.

code

cpp · 12 lines
cpp
#include <string>

struct Particle {
    std::string name;   // non-trivial destructor
    float x = 0;
};

int main() {
    Particle* burst = new Particle[4];
    // ... simulate ...
    delete burst;       // BUG: undefined behaviour - memory from new[] needs delete[]
}

go deeper

for a junior

Recall that new pairs with delete and new[] pairs with delete[], and that mixing them is undefined behaviour, not a minor leak.

for a middle

Explain why delete[] needs the element count, how implementations store it in a cookie, and why the trivially destructible case hides the bug.

for a senior

Diagnose bad-free and alloc-dealloc-mismatch reports, know when sanitizer checks are off by default, and replace hand-written new[] with vector or unique_ptr<T[]>.

for a principal

Ban raw new[] and delete[] in application code through review rules and warnings-as-errors, keeping them only inside audited container or allocator code.

## Two expressions, two pairs of functions C++ has separate forms for single objects and arrays, and each form pairs with its own allocation and deallocation functions: | Expression | Allocation function | Release expression | Deallocation function | |---|---|---|---| | `new T(args)` | `operator new(std::size_t)` | `delete p` | `operator delete(void*)` (or its sized form) | | `new T[n]` | `operator new[](std::size_t)` | `delete[] p` | `operator delete[](void*)` (or its sized form) | The standard makes the pairing a precondition: the operand of `delete` must come from a non-array `new`, and the operand of `delete[]` from an array `new`. Anything else is **undefined behaviour** - not "leaks a bit", not "only skips destructors". ## Where the element count lives `delete[] p` receives only a pointer, yet it must run `~T()` on every element, last to first. The language does not say how the count is recovered; that is the implementation's job. A common technique is an **array cookie**: extra bytes in front of the first element, written by `new[]` and read by `delete[]`. With Apple clang on arm64, replacing `operator new[]` and logging its argument shows the cookie directly: - `new T1[4]` for a 4-byte trivially destructible `T1` requests 16 bytes - no cookie, nothing to destroy; - `new T2[4]` for the same layout plus a user-provided destructor requests 32 bytes - 16 bytes of cookie in front of the elements. So the pointer a `new[]` expression returns is not always the pointer `operator new[]` returned. Plain `delete` on it passes an address **16 bytes inside** the block to `operator delete`, which is exactly what AddressSanitizer reports. Cookie size and contents are an ABI detail; other targets use different layouts. The standard only allows it: it calls the extra bytes **array allocation overhead**, a non-negative unspecified amount by which the result of an array new-expression may be offset from what `operator new[]` returned, and it may vary from one `new` to the next. ## What a mismatch does in practice 1. **Non-trivial destructor, cookie present**: the wrong address reaches the allocator. On this machine, without sanitizers, the system allocator stops the process with a trap; under `-fsanitize=address` the report is `attempting free on address which was not malloc()-ed` with `SUMMARY: AddressSanitizer: bad-free`. 2. **Trivially destructible type, no cookie**: the address is right and many allocators accept it, so the bug is silent. With Apple clang's AddressSanitizer on macOS, the dedicated `alloc-dealloc-mismatch` check stayed quiet for `delete` on a `new float[64]` block until it was enabled with `ASAN_OPTIONS=alloc_dealloc_mismatch=1`. 3. **Destructors**: plain `delete` runs at most one destructor, so every other element's resources - the `std::string` buffers in a particle burst - leak even when nothing crashes. Because outcome 2 is common, "it worked in testing" proves nothing. The program is undefined regardless of what the allocator happens to tolerate. ## Catching it - **Compiler**: Clang warns by default with `-Wmismatched-new-delete` - "'delete' applied to a pointer that was allocated with 'new[]'; did you mean 'delete[]'?" - when the allocation and the delete are visible in the same function. - **Sanitizers**: AddressSanitizer reports `bad-free` for the cookie case and `alloc-dealloc-mismatch` when that check is enabled; the material on sanitizers covers their flags. - **Tracking allocators**: a debug build that replaces the global `operator new[]` and `operator delete` can tag each block and flag a mismatch - the technique a game engine's memory-tracking build uses. ## A second array rule: no polymorphic delete[] Even with the forms matched, `delete[]` has another trap. For a single object, deleting a `Derived` through a `Base*` is fine when `Base` has a virtual destructor. For arrays it is not: the standard says that in an array delete-expression, if the dynamic type of the object is not similar to its static type, the behaviour is undefined. `Base* fx = new Derived[8]; delete[] fx;` is undefined regardless of virtual destructors, because element size and stride come from the static type. Pointer arithmetic over such an array is broken for the same reason. ## The real fix: stop writing new[] `new[]` and `delete[]` in application code are almost always a design smell: - `std::vector<Particle>` owns the elements, knows its size and destroys them correctly; - `std::unique_ptr<Particle[]>` (or `std::make_unique<Particle[]>(n)`) pairs `new[]` with `delete[]` automatically when a fixed-size heap array is really needed; - `std::array<Particle, 4>` avoids the heap when the size is a compile-time constant. Ownership types are covered in their own branch; the point here is that the matching rule is a language rule you cannot see at the `delete` site, which is the strongest argument for never writing either form by hand.

  • If the element type is trivially destructible, is delete on a new[] pointer safe?
    No. It is undefined behaviour for every type; the standard requires the delete form to match the new form. A trivially destructible type often has no array cookie, so the allocator may receive the right address and nothing visibly fails - which is why the bug survives. Another compiler, a debug allocator or a sanitizer with `alloc_dealloc_mismatch` enabled will still report or crash on it.
  • How does delete[] know how many destructors to run?
    The language leaves that to the implementation. Mainstream ABIs store the element count in an array cookie just before the first element when the type has a non-trivial destructor; with Apple clang on arm64 that cookie is 16 bytes. For trivially destructible types no cookie is needed, because no destructors run and the allocator tracks the block size itself.

  • delete on a new[] pointer only skips the other destructors
  • For ints and floats delete and delete[] are interchangeable
  • The standard defines the array cookie layout
  • A sanitizer always catches delete/delete[] mismatches by default
  • delete[] reads the array length from the type of the pointer
open as a page

In C++, what does a new-expression do beyond calling operator new, and what happens if the constructor throws?

level: middleimportance: must knowfreq 62%

basics

~20 s

A new-expression calls an allocation function (operator new) to get raw storage, then constructs the object there. If the constructor throws, the matching deallocation function frees the storage and the exception propagates; no destructor runs.

open as a page

In C++, how does new (std::nothrow) differ from plain new when allocation fails, and what does it not protect against?

level: middleimportance: should knowfreq 50%

basics

~10 s

Plain new reports allocation failure by throwing std::bad_alloc and never returns null; new (std::nothrow) returns a null pointer instead. The nothrow form covers only allocation: a throwing constructor still throws.

open as a page

In C++, after constructing an object with placement new in a buffer, why must you call its destructor explicitly and never delete it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

Placement new constructs an object in storage you already own and allocates nothing. delete would also free memory that never came from operator new, which is undefined, so end the lifetime with p->~T() and release the buffer separately.

open as a page

In a C++ game engine's memory-tracking build, how do you replace the global operator new and operator delete to count allocations, and what must the replacement cover?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Define functions with the exact replaceable signatures at global scope, once, not inline. Cover the forms the code uses - scalar, array, sized, aligned - and never let the throwing operator new return null.

open as a page