Dynamic Memory Allocation Inc++
Dynamic Memory Allocation Inc++
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 -
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 -
o Stack - All the variables that are declared inside any function take memory from the stack.
o Heap - It is unused memory in the program that is generally used for dynamic memory
allocation.
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
The pointer_varible is of pointer data_type. The data type can be int, float, string, char, etc
Example
Initialize memory
For example
We can also use a new operator to allocate a block(array) of a particular data type.
For example
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.
Note
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.
Code
Now as we have allocated the memory dynamically. Let us learn how to delete it.
Delete operator
Syntax:
delete pointer_variable_name
Example
#include <iostream>
int main ()
int* m = NULL;
m = new(nothrow) int;
if (!m)
*m=29;
int size = 5;
if (!arr)
else
arr[i] = i+1;
}
// freed the allocated memory
delete m;
delete f;
delete[] arr;
return 0;
Output
output
Value of m: 29
Value of f: 75.25