0Pricing
C++ Academy · Lesson

Heap Allocation with new/delete

Manage dynamic memory.

Dynamic Memory with new

The new operator allocates an object on the heap (free store) and returns a pointer to it. Heap objects live until you explicitly free them.

#include <iostream>

int main() {
    int* p = new int(42);   // heap allocation
    std::cout << *p << "\n";
    delete p;               // release it
}

Releasing with delete

Every new must be matched by exactly one delete. Forgetting it leaks memory; doing it twice corrupts the heap.

#include <iostream>

int main() {
    double* d = new double(3.5);
    std::cout << *d << "\n";
    delete d;     // exactly once
}

All lessons in this course

  1. Stack Allocation
  2. Heap Allocation with new/delete
  3. Object Lifetime
  4. Common Memory Bugs
← Back to C++ Academy