Dynamic Memory in C++: new, delete and Safe Array Cleanup

Follow an integer and a three-element array from allocation to cleanup. Learn which delete form matches, why aliases dangle, and how standard-library owners simplify the job.

KnowledgeGate Team

Exam prep & CS education

Updated 18 Nov 20265 min read
Dynamic Memory in C++: new, delete and Safe Array Cleanup

Allocating an integer in C++ is easy; deciding which object survives a scope and which delete form belongs to it takes care. A scalar allocation, a three-element array, and their cleanup rules show how lifetime and ownership differ. Learning raw allocation helps you read existing code and diagnose bugs, while normal application code usually delegates ownership to standard-library types that manage the resource lifetime for you.

Dynamic storage outlives the local pointer’s scope

Inside a function, compare int local = 18; with int* p = new int{18};. The variables local and p have automatic storage duration. The separately allocated integer has dynamic storage duration: leaving the function destroys the local pointer but does not clean up that integer.

Here, p holds a pointer to the allocation; *p accesses the integer there. Ownership means responsibility for cleanup. Raw pointer syntax does not record whether a pointer owns anything, so that responsibility must be clear from the surrounding code.

The heap or free store is a useful introductory model, not a mandated physical stack-and-heap layout. Ordinary local values do not need dynamic allocation. These language fundamentals fit alongside pointers and arrays in the Coding & Skills learning paths. For storage-duration categories and construction/destruction order, see C++ object lifetime and storage duration; this article focuses on raw new/delete pairing and alias failure modes.

Trace one integer from new to delete

The program below prints exactly 25, followed by a newline:

cpp
#include <iostream>
int main() {
    int* p = new int{18};
    *p += 7;
    std::cout << *p << '\n';
    delete p;
    p = nullptr;
}

One allocated integer starts at 18. The update computes 18 + 7 = 25, and the output reads that value. Then delete p ends its lifetime and releases its storage. The pointer is dangling until p = nullptr changes it; deletion itself does not reset p.

The storage and initialisation rules come from [expr.new] in the C++ working draft. Plain new int leaves the integer uninitialised; new int{} initialises it to zero. Ordinary throwing allocation reports failure with std::bad_alloc, so a null check is not its default failure-handling mechanism.

Diagram traces an allocated integer from value 18 through update and deletion to a null pointer.

Allocate and update a three-element array

Run this as a separate program:

cpp
#include <iostream>
int main() {
    int n = 3;
    int* marks = new int[n]{10, 20, 30};
    marks[1] += 5;
    int total = 0;
    for (int i = 0; i < n; ++i) total += marks[i];
    std::cout << total << '\n';
    delete[] marks;
    marks = nullptr;
}

The valid indices are 0, 1 and 2. Updating index 1 computes 20 + 5 = 25, changing [10, 20, 30] into [10, 25, 30].

Iteration

Addition

Running total

i = 0

0 + 10

10

i = 1

10 + 25

35

i = 2

35 + 30

65

The output is exactly 65. Index 3 is outside the valid element range. We track n separately because a raw pointer carries no array length. With this same n, new int[n]{} would initialise all three integers to zero; new int[n] would leave them uninitialised.

Match delete to the allocation form

The matching rules are specified in the C++ working draft’s expr.delete clause:

Allocation or pointer state

Matching cleanup

p = new int{18}

delete p;

p = new int[3]{10,20,30}

delete[] p;

int* p = nullptr;

Either delete form affects no object

A mismatch is undefined behaviour. It does not mean “only the first element gets deleted”, and a successful-looking run does not prove correctness.

For class objects, matching deletion also runs the appropriate destructor or destructors. Our integer examples produce no visible destructor output. Neither deleting &local nor deleting an interior pointer such as marks + 1 is valid here.

Keep allocation families separate. Storage obtained with ordinary new or new[] must not be released with free. The comparison in malloc, calloc and realloc in C explains the C allocation family.

Spot leaks, dangling aliases and double deletion

Copying a pointer does not create another integer:

cpp
int* owner = new int{42};
int* alias = owner;
delete owner;
owner = nullptr;

After these statements, owner is null, alias is dangling, and no allocated integer remains alive. Never read *alias or execute delete alias: the first accesses an object whose lifetime has ended, and the second attempts double deletion. Resetting one pointer cannot repair another pointer holding the old address.

Three panels show owner and alias dangling after deletion, then owner reset to nullptr while alias stays dangling.

Now consider broken code that leaks memory:

cpp
int* lost = new int{9};
lost = nullptr;

The allocation remains live, but its only saved pointer is lost. Replace the second statement with delete lost; lost = nullptr;, before discarding the pointer. Doing this afterwards cannot recover the allocation.

A leak loses cleanup access; use-after-free accesses released storage; double deletion tries to release it again. Do not assign predictable outputs to these bugs. An early return can also bypass manual cleanup.

How a test or interview can check this concept

Check your understanding with these cases:

  • What does the three-element example print? 65, because the update changes only index 1 and the loop adds 10 + 25 + 30.

  • Can alias be used after the owner reset? No. Its pointee’s lifetime ended at deletion; setting owner to null does not change that fact.

  • Does replacing delete[] marks with delete marks have a predictable output? No. That version has undefined behaviour, even though the output statement appears before the incorrect cleanup.

Use the language clauses to justify your answers. Trace the object’s lifetime separately from each pointer’s value. If that distinction feels unclear, the C++ tutorial learning path helps you revise pointers and arrays before returning to ownership.

The short version: make ownership automatic

With C++14 or later, use <memory> for this scalar owner:

cpp
#include <memory>
// Inside a function:
auto p = std::make_unique<int>(18);
*p += 7;

The pointed-to value becomes 25. The unique_ptr releases its owned integer when it leaves scope. For the array, use <vector>:

cpp
#include <vector>
// Inside a function:
std::vector<int> marks{10, 20, 30};
marks[1] += 5;

Values become 10, 25 and 30, totalling 65. Do not manually delete storage owned by either wrapper. RAII ties cleanup to an owner object’s lifetime, including scope exit during exception unwinding. C++ Core Guidelines R.11 recommends avoiding explicit new and delete in ordinary ownership code; this is design guidance, not a syntax ban.

Practise by changing the raw array’s n to 4 and its initialiser to {10,20,30,40}. Keep the update: 10 + 25 + 30 + 40 = 105. Predict that output, run it, then rewrite with a vector. For structured concepts, MCQs and coding practice, continue with the C++ Programming course.