Memory in a c++ program is divided into two concepts:

  • The stack: All the variables declared inside the function will use memory from the stack.
  • The heap: This is known as the unused memory of a program. Dynamic memory allocation c++ is applied in a running program.

When declaring variables in C++, the compiler tells the executable file how much memory is needed to run the program. This generated memory can be allocated before the program is run. So that it can provide adequate space. However, in C++, we can allocate the memory dynamically.

Dynamic memory allocation c++ is the allocation of memory for a certain data structure while your code is running. This allows flexible data sizes and dynamic object creation possible. An analogy of this would be saying “Give me my own piece of the memory on this part of the code”. Since you are able to dynamically allocate memory, it is also your responsibility to free up the memory when you have finished with it. Otherwise, you will be creating memory leaks.

A simple example of dynamic memory allocation would be declaring and initializing an integer variable. Dynamic memory is not accessed like normal declared variables but instead accesses through pointers.

#include <iostream>
using namespace std;
 
int main ()
{
 // Pointer initialized with NULL
 double* pointer_value = NULL;
 
 // Request memory for the variable
 pointer_value = new double;
 
 // Store value at allocated address
 *pointer_value = 30000.55;
 cout << "Value of pvalue : " << *pointer_value << endl;
 
 // free up the memory.
 delete pointer_value;
 
 return 0;
}

 

The new keyword allocates the space dynamically. When the dynamic memory is no longer needed, it can be freed for other requests of dynamic memory with the delete keyword. This might only be a simple code example. The real application of dynamic memory is happening behind the scenes. But it’s an important concept that needs to be understood, as it could save your code from major problems.

Share this post