Some situations often arise in programming where the data or input is dynamic in nature, i.e. the number of data items keeps changing during the program execution. Imagine a live scenario where a program is developed to process employee lists of an organization. The list grows as names are added and shrink as names are removed. As the data increases, the memory allocates space to accommodate the additional data items. Such situations in programming require dynamic memory management techniques. This tutorial will teach you dynamically allocate memory within a C++ program.



What Is Memory Allocation?

Memory can be allocated in two ways to store data. These are:

  1. Compile time allocation or static allocation of memory: Where the compiler allocates memory for named variables. The exact size and storage must be known at compile time; size must be constant for array declaration.
  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. 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 significant role in this case.

What is Dynamic Memory Allocation?

Programmers can dynamically allocate storage space while the program is running. Still, 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 manually performing memory management for dynamic memory allocation.

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

  • Stack: All variables declared inside any function take up the stack's memory.
  • Heap: It is the unused memory of the program and can be used to allocate the memory at runtime dynamically.

Allocating Space Using new Operator

To dynamically allocate space, use the unary operator "new", followed by the type. Here is a code snippet showing the use of new:

Example:

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

The statements above are not so helpful as the allocated space has no name. But the following lines 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

C's malloc() function still exists in C++, but it is recommended to avoid using it. The malloc() allocates the 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 the programmer thinks dynamically allocated variables are no longer needed, they can use the delete operator to free up memory space. The syntax to use it is:

Syntax:

delete var_name;

Here's 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

Suppose you want to allocate memory for an array of characters, e.g., a string of 40 characters. You can dynamically allocate memory using the same syntax, as shown below.

Example:

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

Example of another dynamic allocation program using the 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;
}


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram