C++ · Module 7 · Lesson 61 min read

Dynamic Memory: new & delete

Allocating single objects

go
int* p = new int;        // uninitialized int on the heap
int* q = new int(42);    // initialized to 42
int* z = new int{};      // initialized to 0
delete p;                // release

Allocating arrays

ini
int n = 5;
int* arr = new int[n]{};   // size can be a runtime value
delete[] arr;              // MUST use delete[] for arrays

Objects

arduino
Account* acc = new Account("Asha", 1000);   // constructor runs
delete acc;                                  // destructor runs, then memory is freed

The rules ⚠️

RuleBreaking it causes
Every new needs exactly one deletememory leak
new[] ↔ delete[], new ↔ deleteundefined behaviour
Don't use memory after deleteuse-after-free / dangling pointer
Don't delete twicedouble free → crash/corruption
delete nullptrsafe, does nothing ✅

Set pointers to nullptr after deleting if they stay in scope.

When new fails

It throws std::bad_alloc (or returns nullptr with new (std::nothrow)).

Why raw new/delete is risky

If an exception or early return happens between new and delete, the delete never runs → leak.

ini
Report* r = new Report;
if (!r->load()) return;   // ❌ leak
delete r;

Modern C++: avoid raw new/delete ✅

Instead ofUse
new T[n]std::vector<T>
new T (single owner)std::make_unique<T>()
new T (shared)std::make_shared<T>()
These release memory automatically (RAII, Unit 11).

Finding memory bugs

Compile with -fsanitize=address or run under Valgrind — they report leaks, use-after-free and double free with exact line numbers.

Example

C++
#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Account {
    std::string owner;
    double balance;
    Account(std::string o, double b) : owner(std::move(o)), balance(b) {
        std::cout << "  [open " << owner << "]\n";
    }
    ~Account() { std::cout << "  [close " << owner << "]\n"; }
};

int main() {
    int* single = new int(42);
    std::cout << "single = " << *single << '\n';
    delete single;
    single = nullptr;                     // avoid a dangling pointer
    delete single;                        // deleting nullptr is safe

    int n = 5;
    int* squares = new int[n]{};          // runtime-sized array
    for (int i = 0; i < n; ++i) squares[i] = i * i;
    std::cout << "squares:";
    for (int i = 0; i < n; ++i) std::cout << ' ' << squares[i];
    std::cout << '\n';
    delete[] squares;                     // [] for arrays

    std::cout << "Raw new/delete:\n";
    Account* raw = new Account("Asha", 1000);
    raw->balance += 500;
    std::cout << "  " << raw->owner << " has " << raw->balance << '\n';
    delete raw;                           // destructor runs here

    std::cout << "Modern alternatives:\n";
    {
        std::vector<int> v(n);            // replaces new int[n]
        auto acc = std::make_unique<Account>("Ravi", 2000);   // replaces new Account
        std::cout << "  " << acc->owner << " has " << acc->balance << '\n';
    }                                     // both released automatically here
    std::cout << "done\n";
    return 0;
}

/* Output:
single = 42
squares: 0 1 4 9 16
Raw new/delete:
  [open Asha]
  Asha has 1500
  [close Asha]
Modern alternatives:
  [open Ravi]
  Ravi has 2000
  [close Ravi]
done
*/