Dynamic Memory Allocation

Allocate an array with an unpredictable number of elements

When you use a declaration to create an array in C++, you must always specify the number of elements in the array when you write the program. Here are two ways to do that. (Use the data type size_t for a variable that holds the number of elements in an array, or the number of bytes in a block of memory.)

	int a[3];   //Create an array containing 3 elements.

	int b[] {   //Create another array containing 3 elements.
		10,
		20,
		30
	};

	//If you need a variable holding the number of elements in the array b,
	const size_t n {size(b)};

If you don’t know the number of elements when you write the program, then you can’t use a declaration to make an array. For example, you can’t get the number of elements from input after the program has started running:

	cout << "How many elements do you need in your array? ";
	size_t n {0};
	cin >> n;
	int a[n];   //Try to create an array with n elements.  Won't compile.

The simplest application of dynamic memory allocation (written with the operators new and delete[]) is to create an array when you can’t predict when you’re writing the program how many array elements you will need.

  1. new1.C, new1.txt.
    Loop through the block of memory with a size_t i subscript. Not bothering to check cin for input failure.
  2. new2.C, new2.txt.
    Loop through the block of memory with an int *q pointer.
    What happens if the user requests too much dynamically allocated memory?
    How many ints do you want to store? 99999999999
    terminate called after throwing an instance of 'std::bad_alloc'
      what():  std::bad_alloc
    Aborted (core dumped)
    
    echo $?     (See the exit status number producted by the program.)
    134         (134 = 128 + 6.  6 is number of the abort signal SIGABRT.)
    
  3. new3.C. Catch the bad_alloc exception.
    How many ints do you want to store? 99999999999        (almost 100 billion)
    Sorry, Linux has no room for 99999999999 ints.         (civilized error message)
    
    echo $?                                                (civilized exit status)
    1
    

Use a vector object instead of new and delete[]

  1. vectorint.C, vectorint.txt.
    Easier to use a C++ standard library vector object instead of new and delete[], and we don’t have to tell the program up front how many items we want to store.
    v is our first example of an object.
    The name of the data type of this object is std::vector<int>. (A data type that has a pair of <angle brackets> in its name is a template data type.)
    We can loop through a vector with the same range for loop that we used to loop through an array. See range.C, range.txt.
    I’m demonstrating two of the member functions of v, push_back and size.
    Exercise.
    Uncomment the following statements in vectorint.C immediately after the call to the push_back member function.
    		cout << "v.size() = " << v.size() << "\n";
    		cout << "v.capacity() = " << v.capacity() << "\n";
    
    Does the vector’s capacity grow faster than its size? Does the capacity ever suddenly double as the vector increases in size?
  2. Since class vector is a template class, we can easily make a vector containing doubles instead of ints. The push_back member function of this vector takes an argument that its a double, and the auto variable in this range for loop is a const double&. I made it a const double& because a double is more expensive to copy than an int.
    vectordouble.C, vectordouble.txt.
  3. The C++ Standard Library contains many other container classes that are template classes. For example,
    1. Use a vector when you want to add new values only to the end of the container (via push_back).
    2. Use a list when you want to add new values in the middle of the container (via insert).

Kill your variables in an unpredictable order

  1. The order in which variables are declared determines the order in which they die:
    #include <cstdlib>
    
    int main()
    {
    	int i {10};
    	int j {20};
    	int k {30};
    
    	return EXIT_SUCESS; //k, j, i die here, in that order.
    }
    

    But is we have a game where the variables are Klingon warships, you probably can’t know in advance what order they will be destroyed in. It depends on what the user decied to do when the program runs. You will have to create each variable with new instead of with a declaration. (And you will have to remember to write delete at each point where a variable dies.) We will do this later in the course.