Dynamic Memory Allocation

Allocating memory

There are two ways that memory gets allocated for data storage:
  1. Compile Time (or static) Allocation
  2. Dynamic Memory Allocation

Dynamic Memory Allocation

Allocating space with new

Accessing dynamically created space

Deallocation of dynamic memory


Application Example: Dynamically resizing an array

If you have an existing array, and you want to make it bigger (add array cells to it), you cannot simply append new cells to the old ones.  Remember that arrays are stored in consecutive memory, and you never know whether or not the memory immediately after the array is already allocated for something else.   For that reason, the process takes a few more steps.  Here is an example using an integer array.  Let's say this is the original array:
 int * list = new int[size];   

I want to resize this so that the array called list has space for 5 more numbers (presumably because the old one is full).
There are four main steps.

  1. Create an entirely new array of the appropriate type and of the new size. (You'll need another pointer for this).
     int * temp = new int[size + 5];   
  2. Copy the data from the old array into the new array (keeping them in the same positions). This is easy with a for-loop.
     for (int i = 0; i < size; i++)       temp[i] = list[i];   
  3. Delete the old array -- you don't need it anymore! (Do as your Mom says, and take out the garbage!)
     delete [] list;  // this deletes the array pointed to by "list" 
  4. Change the pointer. You still want the array to be called "list" (its original name), so change the list pointer to the new address.
     list = temp;   

That's it! The list array is now 5 larger than the previous one, and it has the same data in it that the original one had. But, now it has room for 5 more items.