C++ Dynamic Memory

In this C++ programming tutorial we will take a look at dynamic memory. Until now the use of memory was determined by the size of the variable we declared. With the use of dynamic memory we can ask for a piece of memory at runtime. In C++ we can use the operators new and delete to get memory and release the memory.

new and new[] operators

With the operator new we can request a piece of memory. A data type must follow the new operator. It is also possible to request more than one element by using brackets []. The result of a new operation is a pointer to the beginning of the memory block (if the request is accepted).

So we can do the following:

  • Some_pointer= new type;
  • Some_pointer= new type [number];

With the first expression only one element of the type “type” is requested (for example of the type int). The second expression will request a number of elements of a specific type. Take a look at an example:


	int * ptr_mypointer;
	ptr_mypointer = new int[10];

Note: First we declare a pointer. Then we ask for ten elements of the type int. (In most cases int = 32bits = 4bytes = 4bytes times ten = 40bytes.) If the request is granted the pointer will point to the first element of the piece of memory.

With the expression ptr_mypointer[0] or *ptr_mypointer we can access the first element. With ptr_mypointer[1] or *(ptr_mypointer+1) we can access the second element (and so on).

The difference between a normal array and assigning dynamic memory to a pointer is that a normal array has a constant value. (The size of an array is decided when you make the program.) With dynamic memory allocation you ask for memory at execution time.

The operator new([]) will allocate a certain amount of memory during the execution of a program. The new([]) operator will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory. So it is important to check if the request is granted.
The C++ language provides two standard methods to do this:

  • Handling exceptions
  • nothrow method

Handling exceptions: if an allocation is not granted (fails) an exception of the type bad_alloc is given.
(Exception will be explained in a later tutorial.) For now it is enough to know that if an exception occurs and a specific handler does not handle it, the program execution will be terminated.

The exception method is the default method that is used by the new function. When you use new during a declaration, then exceptions will be thrown if the request fails.

The second method (nothrow) can be used instead of bad_alloc exception. By specifying a special object (called nothrow) as a parameter for new, the new function will return a NULL pointer if the request fails.
Take a look at an example:


int * ptr_mymem;
	ptr_mymem = new (nothrow) int [10];
	if (ptr_mymem == 0)
	{
		// Some action(exit or smaller request)!
	}

Note: if the memory allocation fails, you must take some measures. In smaller projects the nothrow method is preferred because of it simplicity.

delete and delete[] operators

If a memory request is granted, the operating system will reserve the requested amount of memory. When the amount of memory is not needed anymore, you must return it to the operating system by calling the operator delete.

The operator delete also comes in two formats. Take a look:

  • delete pointer;
  • delete[] pointer;

With the first format one element can be freed and with the second format an array of elements can be freed. The pointer used with delete must be a pointer to a memory block that was allocated earlier with the new operator. It is also possible to use a null pointer. However this will have no effect.

Take a look at a complete example:


	#include <iostream>
	using namespace std;

	int main ()
	{
		int max_num, count;
		int * ptr_mymem;

		cout << "How many numbers? ";
		cin >> max_num;
		ptr_mymem = new (nothrow) int[max_num];
		if (ptr_mymem == 0)
		{
			cout << "Memory not available!";
			return 1;
		}
		else
		{
			for (count=0; count < max_num; count++)
			{
				cout << "Enter a number: ";
				cin >> ptr_mymem[count];
			}
			cout << "You have entered the numbers: ";
			for (count=0; count < max_num; count++)
				cout << ptr_mymem[count] << ", ";

			delete[] ptr_mymem;
		}
		return 0;
	}

Note: To test the nothrow method you can enter a very large number to see the error.

ANSI-C and dynamic memory

The operators new and delete can only be used in the C++ language. It is also possible to use malloc and free from the C language in C++.

Read the C tutorial on dynamic memory here.

That is all for this tutorial.

This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

Leave a Reply: