C++ Dynamic Memory Allocation
Dynamic memory allocation means allocating memory for program into run time. The run time allocation for memory is done during the program execution. In dynamic memory allocation, the heap data structure is used for allocating memory. Memory is reusable when we use dynamic memory allocation. More efficient way to allocate memory dynamically than static memory allocation. We can easily free the allocate space in case of dynamic memory allocation.
Two operator manages the dynamic memory allocation in C++ programming language:
- new
- delete
new Operator
new operator dynamically allocate the memory of C++. In dynamic memory allocation, new operator follows the heap data structure to allocate the memory.
Syntax of new operator(single_element):
Syntax:
pointer = new data_type;
Syntax of new operator(multiple_element or array):
Syntax:
pointer = new data_type [number_of_elements];
Example of new operator using the single_element.
Example:
int *p; // declares a pointer p
p = new int; // dynamically allocate an int for loading the address in p
Example of new operator using the multiple_element or array.
Example:
int *p; // declares a pointer p
p = new int[10]; // dynamically allocate an arry element of int for loading the address in p
Here is a program example of dynamic memory allocation using new operator.
Example:
#include <iostream>
#include <new>
using namespace std;
int main() {
int *ptr
int a, b;
a = 20;
// Dynamically allocate memory using new operator
ptr = new int[a];
if (ptr == NULL) {
cout << "Memory is not allocated.\n";
}
else {
cout << "Successfully allocated memory using new operator.\n";
for(b = 0; b < a; ++b) {
ptr[b] = b + 1;
}
for(b = 0; b < a; ++b) {
cout << ptr[b];
}
}
return 0;
}
delete Operator
delete operator de-allocate the memory that is allocated through new operator.
Syntax of delete operator(single_element):
Syntax:
delete pointer_name;
Syntax of delete operator(multiple_element or array):
Syntax:
delete[] pointer_name;
Here is a program example of dynamic memory allocation using delete operator.
Example:
#include <iostream>
#include <new>
using namespace std;
int main() {
int *ptr
int a, b;
a = 20;
// Dynamically allocate memory using new operator
ptr = new int[a];
if (ptr == NULL) {
cout << "Memory is not allocated.\n";
}
else {
cout << "Successfully allocated memory using new operator.\n";
for(b = 0; b < a; ++b) {
ptr[b] = b + 1;
}
for(b = 0; b < a; ++b) {
cout << ptr[b];
}
}
// dynamically allocate memory deleted
delete[] ptr;
return 0;
}