C++ Dynamic Memory Allocation

Often some situation arises in programming where data or input is dynamic in nature, i.e. the number of data item keeps changing during program execution. A live scenario where the program is developed to process lists of employees of an organization. The list grows as the names are added and shrink as the names get deleted. With the increase in name the memory allocate space to the list to accommodate additional data items. Such situations in programming require dynamic memory management techniques.

In this chapter, you will learn about how to dynamically allocate memory within a C++ program.

What is memory Allocation?

There are two ways via which memories can be allocated for storing data. The two ways are:

  1. Compile time allocation or static allocation of memory: where the memory for named variables is allocated by the compiler. Exact size and storage must be known at compile time and for array declaration, the size has to be constant.
  2. Runtime allocation or dynamic allocation of memory: where the memory is allocated at runtime and the allocation of memory space is done dynamically within the program run and the memory segment is known as a heap or the free store. In this case, the exact space or number of the item does not have to be known by the compiler in advance. Pointers play a major role in this case.

What is Dynamic memory allocation?

Programmers can dynamically allocate storage space while the program is running, but programmers cannot create new variable names "on the fly", and for this reason, dynamic allocation requires two criteria:

  • Creating the dynamic space in memory
  • Storing its address in a pointer (so that space can be accessed)

Memory de-allocation is also a part of this concept where the "clean-up" of space is done for variables or other data storage. It is the job of the programmer to de-allocate dynamically created space. For de-allocating dynamic memory, we use the delete operator. In other words, dynamic memory Allocation refers to performing memory management for dynamic memory allocation manually.

Memory in your C++ program is divided into two parts:

  • stack: All variables declared inside any function takes up memory from the stack.
  • heap: It is the unused memory of the program and can be used to dynamically allocate the memory at runtime.

Allocating space for new

To allocate space dynamically, use the unary operator new, followed by the type being allocated.

Here is a code snippet showing the use of new:

new int; //dynamically allocates an integer type
new double; // dynamically allocates an double type
new int[60];

The above-declared statements are not so useful as the allocated space has no names. But the lines written below are useful:

int * p; // declares a pointer p
p = new int;  // dynamically allocate an int for loading the address in p
double * d;  // declares a pointer d
d = new double;  // dynamically allocate a double and loading the address in p

The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. malloc() allocates requested size of bytes and returns a pointer to the first byte of allocated space. The main benefit of new over malloc() is that new doesn't just allocate memory, it constructs objects which is a prime concept of C++. When programmers think that the dynamically allocated variable is not required anymore, they can use the delete operator to free up memory space. The syntax of using this is:

delete var_name;

Here is a simple program showing the concept of dynamic memory allocation:

Example:
#include <iostream>
using namespace std; 

int main()
{
    double* val = NULL;
    val = new double;
    *val = 38184.26;
    cout << "Value is : " << *val << endl;
    delete val;
}

Dynamic Memory Allocation for Arrays

If you as a programmer; wants to allocate memory for an array of characters, i.e., a string of 40 characters. Using that same syntax, programmers can allocate memory dynamically as shown below.

char* val  = NULL;       // Pointer initialized with NULL value
val = new char[40];     // Request memory for the variable

Another Dynamic Allocation Program Using Constructor

Example:
#include <iostream>
using namespace std; 

class stud {
public:
    stud()
    {
        cout << "Constructor Used" << endl;
    }
    ~stud()
    {
        cout << "Destructor Used" << endl;
    }
};

int main()
{
    stud* S = new stud[6];
    delete[] S;
}

Here are few other related articles for you to read:

Scroll Back to Top