Dynamic Memory: new and delete

Normal variables disappear automatically at the end of their { } block. Sometimes you want to create something while the program runs and decide yourself when it goes away. That's what new does. It reserves memory on the heap and gives you a pointer to it:

#include <iostream>
using namespace std;

int main() {
    int* p = new int(42);       // make a new int on the heap
    cout << *p << "\n";
    *p += 8;
    cout << *p << "\n";
    delete p;                   // give the memory back
    p = nullptr;                // good habit: don't keep a pointer to freed memory
    return 0;
}

Output

42
50

Arrays with a size chosen at run time

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int* squares = new int[n];        // n is only known now
    for (int i = 0; i < n; i++) {
        squares[i] = (i + 1) * (i + 1);
    }
    for (int i = 0; i < n; i++) {
        cout << squares[i] << " ";
    }
    cout << "\n";
    delete[] squares;                 // [] because it was new[]
    return 0;
}

Input (what the user types)

5

Output

1 4 9 16 25 

Think of it like this: new is like renting a storage unit: it's yours until you hand back the key with delete. Forget to hand it back and you keep paying for it.

Common mistake: Forgetting delete causes a memory leak: the memory stays reserved until the program ends. Using memory after delete (a use-after-free) is even worse, and is a classic security bug.

Remember: Modern C++ rarely uses new/delete directly. vector and smart pointers (Module 13) clean up automatically. It's still important to understand what they do for you.

HOME LABS COMMUNITY DASHBOARD