Dynamic memory allocation in C++
There are times where the data to be entered is allocated at the time of execution. For example, a list of employees increases as the new employees are hired in the organization and similarly reduces when a person leaves the organization. This is called managing the memory. So now, let us discuss the concept of dynamic memory allocation.
Reserving or providing space to a variable is called memory allocation. For storing the data, memory allocation can be done in two ways -
Why Dynamic memory allocation?
Dynamically we can allocate storage while the program is in a running state, but variables cannot be created "on the fly". Thus, there are two criteria for dynamic memory allocation -
Similarly, we do memory de-allocation for the variables in the memory.
In C++, memory is divided into two parts -
Dynamic memory allocation using the new operator
To allocate the space dynamically, the operator new is used. It means creating a request for memory allocation on the free store. If memory is available, memory is initialized, and the address of that space is returned to a pointer variable.
Pointer_variable = new data_type;
The pointer_varible is of pointer data_type. The data type can be int, float, string, char, etc.
int *m = NULL // Initially we have a NULL pointer
m = new int // memory is requested to the variable
It can be directly declared by putting the following statement in a line -
int *m = new int
We can also initialize memory using new operator.
int *m = new int(20);
Float *d = new float(21.01);
Allocate a block of memory
We can also use a new operator to allocate a block(array) of a particular data type.
int *arr = new int
Here we have dynamically allocated memory for ten integers which also returns a pointer to the first element of the array. Hence, arr is the first element and so on.
Now as we have allocated the memory dynamically. Let us learn how to delete it.
We delete the allocated space in C++ using the delete operator.
delete m; // free m that is a variable
delete  arr; // Release a block of memory
Example to demonstrate dynamic memory allocation
Value of m: 29 Value of f: 75.25 Value store in block of memory: 1 2 3 4 5