C++ Programming: Objects, RAII and the STL · Memory and Ownership

new and delete

Create values and objects on the heap with new, and release them with delete or delete[].

new_delete.cpp

#include <iostream>
using namespace std;

struct Point {
    int x, y;
};

int main() {
    int *n = new int(42);          // one int on the heap
    Point *p = new Point{3, 4};    // one object on the heap
    int *arr = new int[3]{7, 8, 9};
    p->x = 10;
    int total = *n + p->x + arr[2];
    delete n;                      // every new needs a delete
    delete p;
    delete[] arr;                  // arrays need delete[]
    cout << total << endl;
    return 0;
}

Step by step

  1. new int(42) puts one int on the heap; n holds its address.
  2. A Point on the heap.
  3. An array of 3 ints on the heap.
  4. x in the Point that p points to changes from 3 to 10.
  5. total is created on the stack with the value 61.
  6. delete n releases the int.
  7. p changes from {x: 10, y: 4} to → freed memory (dangling).
  8. arr changes from [7, 8, 9] to → freed memory (dangling).
  9. n now points to a different int: -1414812927. p now points to a different Point[3]: [{x: 7797744, y: 0}, {x: 0, y: 0}, {x: 0, y: 0}]. arr now points to a different int[12]: [-1162743571, 0, 0, 0, 0, 0, 7771744, 0, …]. It prints 61.
  10. The method returns 0.
  11. 61 (42 + 10 + 9), and every heap block released.