What is Dynamic Memory Allocation?
Dynamic Memory allocation means that the memory that will be used during the program is not known beforehand and is allocated dynamically and on the go. It is allocated during the runtime as and when required by the program.
In C++ there are two operators used in dynamic memory allocation
1. New
2. Delete
New operator in dynamic memory allocation
The new operator in C++ is used to create objects of all types. The new operator will allocate memory of the size of the data type specified in the program.
For Example
iptr = new int ;
Storing initial values will allocate needed amount of memory from the free store to hold the value of the specified data-type and store the starting address of the newly allocated memory in iptr.
By default operator new returns 0 (NULL) when insufficient free store is available to satisfy its request.
Delete operator in dynamic memory allocation
This is a much-needed operator in the dynamic memory allocation process. When an object that is created by the use of new operator is no longer needed, then the delete operator comes in handy.
When an object is no longer needed it needs to be deleted to release the allocated memory, this is done by the use of the delete operator.
For Example
delete pointer-variable ;
Here pointer-variable is the pointing to the data object created with new. As we have created above iptr.
so the delete operator will be as follow :
delete iptr ;