Dynamic Memory in C++

See also Pointers and Pass by Reference in C++ Basics.

Dynamic Memory Management in C++

Declaring class objects on the stack works similarly to primitive types:

Dynamic allocation and deallocation of variables on the heap requires the use of keywords new and delete:

int * ip = new int;            // allocate memory for integer
MyClass * c = new MyClass();   // allocate object and return pointer to address
delete c;                      // free the heap memory for the object
delete ip;                     // free the heap memory for the integer

Dynamic arrays

We also use new/delete to manage heap memory for arrays in C++. Arrays of primitive type elements are fairly straightforward. Elements in a dynamically allocated array of primitive type are not initialized by default (similar to malloc).

  int *iray = new int[n];         // makes array of n ints on heap
  // ...
  delete [] iray;                 // frees memory of array, note use of [ ] in statement!

Arrays of objects are initialized automatically using (necessary) default constructors: MyClass * array = new MyClass[6];

MyClass * array = new MyClass[6];
for (int i=0; i < 6; i++)
    array[i] = MyClass(7, 'd'); // fresh object made, overwrites new objects above

delete [] array;    // remember to delete with [] for any array on the heap