Dynamic Memory Allocation

The real power of pointers arises when pointers are used with special kinds of variables called dynamically allocated variables, or simply, dynamic variables.

Dynamic variables are like ordinary variables, with TWO important differences:

  1. they are not declared
  2. they are created during the execution of a program

To create a dynamic variable (ie. allocate memory), use the new operator:

   Format: pointer_variable = new data_type;

The new operator automatically:

To create and initialize a newly allocated object:

   Format: pointer_variable = new data_type (initial_value);

Dynamic Memory Allocation and Arrays

Up to this point, the new operator has been used to allocate a single variable. It can also be used to allocate memory for an entire array.

   Format: pointer_variable = new data_type[# of elements];

When the array is allocated, the address of the first element will be stored in the pointer variable. Even though the array, was created using new, it can still be accessed using standard array notation with the pointer variable.


Dynamic Memory Allocation and Classes

Memory for a class member can also be allocated using the new operator.

Format: class_name * pointer_variable;

        pointer_variable = new class_name;      //uses the default constructor

        pointer_variable = new class_name(int);    //use a constructor that takes
                                                   //1 integer argument

"Freeing up" Dynamically Allocated Memory

Once dynamically memory is no longer needed, it should be "freed up" (or deallocated) so that it can be used for something else. To deallocate memory, use the delete operator

   Format 1: delete pointer_variable;

   Format 2: delete [] pointer_variable;

A few rules about the delete operator:

  1. Can ONLY be used on memory that was allocated with new

  2. Cannot deallocate memory that has previously been deallocated

  3. Using delete on null pointer has no effect