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.
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 -
- Static allocation or compile-time allocation - Static memory allocation means providing space for the variable. The size and data type of the variable is known, and it remains constant throughout the program.
- Dynamic allocation or run-time allocation - The allocation in which memory is allocated dynamically. In this type of allocation, the exact size of the variable is not known in advance. Pointers play a major role in dynamic memory allocation.
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 -
- A dynamic space in the memory is needed.
- Storing the address to access the variable from the memory
Similarly, we do memory de-allocation for the variables in the memory.
In C++, memory is divided into two parts -
- Stack - All the variables that are declared inside any function take memory from the stack.
- Heap - It is unused memory in the program that is generally used for dynamic memory allocation.
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.
Syntax
Pointervariable = new datatype;
The pointervarible is of pointer datatype. The data type can be int, float, string, char, etc.
Example
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
Initialize memory
We can also initialize memory using new operator.
For example
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.
For example
int *arr = new int[10]
Here we have dynamically allocated memory for ten integers which also returns a pointer to the first element of the array. Hence, arr[0] is the first element and so on.
- The difference between creating a normal array and allocating a block using new normal arrays is deallocated by the compiler. Whereas the block is created dynamically until the programmer deletes it or if the program terminates.
- If there is no space in the heap memory, the new request results in a failure throwing an exception(std::bad_alloc) until we use nonthrow with the new operator. Thus, the best practice is to first check for the pointer variable.
int *m = new(nonthrow) int;
if(!m) // check if memory is available
{
cout<< "No memory allocated";
}
Now as we have allocated the memory dynamically. Let us learn how to delete it.
Delete operator
We delete the allocated space in C++ using the delete operator.
Syntax
delete pointervariablename
Example
delete m; // free m that is a variable
delete arr; // Release a block of memory
Example to demonstrate dynamic memory allocation
// The program will show the use of new and delete
#include <iostream>
using namespace std;
int main ()
{
// Pointer initialization to null
int* m = NULL;
// Request memory for the variable
// using new operator
m = new(nothrow) int;
if (!m)
cout<< "allocation of memory failed\n";
else
{
// Store value at allocated address
*m=29;
cout<< "Value of m: " << *m <<endl;
}
// Request block of memory
// using new operator
float *f = new float(75.25);
cout<< "Value of f: " << *f <<endl;
// Request block of memory of size
int size = 5;
int *arr = new(nothrow) int[size];
if (!arr)
cout<< "allocation of memory failed\n";
else
{
for (int i = 0; i< size; i++)
arr[i] = i+1;
cout<< "Value store in block of memory: ";
for (int i = 0; i< size; i++)
cout<<arr[i] << " ";
}
// freed the allocated memory
delete m;
delete f;
// freed the block of allocated memory
delete[] arr;
return 0;
}
Output
Value of m: 29
Value of f: 75.25
Value store in block of memory: 1 2 3 4 5