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:

  1. new
  2. 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:

  1. pointer = new data_type;

Syntax of new operator(multiple_element or array):

Syntax:

  1. pointer = new data_type [number_of_elements];

Example of new operator using the single_element.

Example:

  1. int *p; // declares a pointer p
  2. p = new int; // dynamically allocate an int for loading the address in p

Example of new operator using the multiple_element or array.

Example:

  1. int *p; // declares a pointer p
  2. 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:

  1. #include <iostream>
  2. #include <new>
  3. using namespace std;
  4. int main() {
  5. int *ptr
  6. int a, b;
  7. a = 20;
  8. // Dynamically allocate memory using new operator
  9. ptr = new int[a];
  10. if (ptr == NULL) {
  11. cout << "Memory is not allocated.\n";
  12. }
  13. else {
  14. cout << "Successfully allocated memory using new operator.\n";
  15. for(b = 0; b < a; ++b) {
  16. ptr[b] = b + 1;
  17. }
  18. for(b = 0; b < a; ++b) {
  19. cout << ptr[b];
  20. }
  21. }
  22. return 0;
  23. }


delete Operator

delete operator de-allocate the memory that is allocated through new operator.
Syntax of delete operator(single_element):

Syntax:

  1. delete pointer_name;

Syntax of delete operator(multiple_element or array):

Syntax:

  1. delete[] pointer_name;

Here is a program example of dynamic memory allocation using delete operator.

Example:

  1. #include <iostream>
  2. #include <new>
  3. using namespace std;
  4. int main() {
  5. int *ptr
  6. int a, b;
  7. a = 20;
  8. // Dynamically allocate memory using new operator
  9. ptr = new int[a];
  10. if (ptr == NULL) {
  11. cout << "Memory is not allocated.\n";
  12. }
  13. else {
  14. cout << "Successfully allocated memory using new operator.\n";
  15. for(b = 0; b < a; ++b) {
  16. ptr[b] = b + 1;
  17. }
  18. for(b = 0; b < a; ++b) {
  19. cout << ptr[b];
  20. }
  21. }
  22. // dynamically allocate memory deleted
  23. delete[] ptr;
  24. return 0;
  25. }