Dynamic Memory in C++

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 and where dynamic memory allocation is applied in a running program

When declaring variables in C++, the compiler will tell the executable file it generates how much memory is going to be needed to run the program. This generated memory can be allocated before the program is run, so that it can provide adaquate space. However in C++, we can allocate the memory dynamically.

Dynamic memory allocation 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 initliazing an integer varaible. Dynamic memory is not accessed like normal declared variables, but instead accesses through pointers.

</pre>
<pre class="prettyprint notranslate tryit prettyprinted">#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;
}</pre>
<pre>

The new keyword allocates the space dynamically and when the dynamic memory is no longer needed, it can be freed for other request of dynamic memory with the delete keyword. This might only be a simple code example, as the real application of dynamic memory is happenning 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