C++ Dynamic Memory

C++ Dynamic memory is run time memory that generates on runtime. There may come situation when program takes user input and the nature of user input is unknown. In this situation, memory is allocated dynamically. It is run time or dynamic memory allocation. Usually, compiler allocates the memory is on compile time. In most cases memory of each variable or array is defined beforehand. This is compile time or static memory allocation.

There are two types of memories in C++ programming language:

  • Stack
  • Heap

Stack

The memory that is allocated for all the variables defined in a program is Stack. Stack provides compile time memory allocation.

Heap

The memory that is allocated for the program but is not used is Heap. It allocates memory at run time. It is used for dynamic memory allocation.

Consider a real time example of a list of students. The length of list of students is equal to the number of students. So it depends on the names of students entered by user. It could be 2, 4, 5, 10 and so on. Programmer can use dynamic memory allocation for such data types. C++ programming language uses new and delete operators to allocate memory dynamically. Pointers use these operators for dynamic memory allocation.

Using new Operator

New operator creates a new object of the data type which is an essence of object oriented programming OOP. The syntax for declaring dynamic memory using new operator is:

Here new is a keyword and data_type can be any one of the data types that C++ programming language allows. Data type can also be one of user defined data types like class and structure or arrays.

For example the below code allocates memory for int and double type variables:

new int;
new double;

In the above example, programmer cannot access the declared dynamic memory. Pointers are used to access dynamic memory. Pointers point to the beginning of memory block. The syntax is:

In the first statement, pointer points to a single block of memory. While in the second statement, pointer points to an array. Here pointer_name is a pointer and integer is the number of elements. For example, the below code shows how to initialize a pointer to an array of dynamic array.

int * ptr;
ptr = new int [6];

In the above example, pointer ptr points to the array having 6 elements that user will define on run time.

Using delete Operator

Along with memory allocation, dynamic memory deallocation is also necessary. Memory deallocation is destroying the dynamic memory after it is not usable. In C++ programming language, the keyword delete de-allocates the dynamic memory. It cleans up the space occupied by variable or pointer. The syntax for using delete operator is:

Here pointer_name is the name of pointer. The delete operator dumps its dynamic memory. For example, the simple code below shows how to allocate dynamic memory using new operator and how to de-allocate it using delete operator.

#include <iostream>
using namespace std; 
int main()
{
    double* ptr = NULL;
    ptr = new double;
    *ptr = 3.42543;
    cout << "Value is of pointer is: " << *ptr << endl;
    cout << "Memory is allocated at: " << ptr << endl;
    delete ptr;
}

Note that the best practice is to declare the pointer as NULL. The output of the above code after compilation is:

To de-allocate memory of an array, following is the syntax:

C++ Dynamic Memory Allocation using Arrays

Here arr is the name of array. Below is another example that shows how to allocate and de-allocate memory for an array.

#include <iostream>
using namespace std;
int main() {
	int i, num;
	cout << "Enter the number of elements:" << "\n";
	cin >> num;
	int *arr = new int[num];
	cout << "Enter " << num << " elements" << endl;
	for (i = 0; i < num; i++) {
		cin >> arr[i];
	}
	cout << "Elements entered are: ";
	for (i = 0; i < num; i++) {
		cout << arr[i] << " ";
	}
	delete [] arr;
	return 0;
}

The output of the above code after compilation is:

C++ Dynamic Memory Allocation using Constructors

The below example shows C++ dynamic memory allocation and de-allocation using constructor.

#include <iostream>
using namespace std; 
class A {
public:
    A()
    {
        cout << "Constructor Called" << endl;
    }
    ~A()
    {
        cout << "Destructor Called" << endl;
    }
};
int main()
{
    A* obj = new A[5];
    delete[] obj;
}

Here class A has an object obj. The object obj is an array of 5 objects of class A. In the program, the constructor is called five times. The output of the above code after compilation is: