Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
New & Delete Operators
3.
Dynamic Memory Allocation for Arrays
3.1.
To create and allocate an array
3.2.
To de-allocate and remove the array
4.
Dynamic Memory Allocation for Objects
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Dynamic Memory

Introduction

Any computer program written in any language needs some memory in order to be executed. In C++, dynamic memory allocation refers to manually allocating memory by the programmer. Many times, the programmer is not aware of the amount of memory required to store information, or the number of data items keeps changing. In such a scenario dynamic memory comes in handy.
 

Dynamically we can allocate memory while the program is still running, but the variables cannot be created during the execution of the program, because of which there are two criteria for dynamic memory allocation:

  • A section in memory is needed which can be used as a dynamic space
  • We need to store the address so that we can access the variable from memory when required.

 

Apart from allocating memory, we also need to de-allocate the memory which was earlier allocated. It is the responsibility of the programmer to de-allocate dynamically created space, it is not done by the compiler.

For e.g., when we create a normal variable like ‘int x’ memory is automatically allocated and de-allocated without any interference of the programmer, but when we allocate memory dynamically like ‘int *x=new int[5]’, now it is the programmer's responsibility to de-allocated the memory allocated for it when it is no longer needed.

Also see, Literals in C.Fibonacci Series in C++

New & Delete Operators

The new operator is a special operator used in C++ to allocate memory at run time within the heap for the variable of a given type, and it returns the address of the space allocated. The new operator basically denotes a request for memory allocation, if sufficient memory is available, it initializes the memory and returns the address of the allocated memory.

Since it is the responsibility of the programmer to de-allocate the memory, the delete operator is used. Whenever a programmer feels that the variable that has been dynamically allocated is not required anymore, the programmer can free the memory occupied by the variable using the ‘delete’ operator.

Syntax

pointerVariable = new dataType;

 

New operator can be used with any built-in data type as well as custom data types also, which are defined using class or structure to allocate dynamic memory.

E.g.,  int *x=new int

Because C++ is the superset of the C programming language, it also has malloc() function, but it is preferred to use new over malloc(), as new allocates memory as well as constructs objects which is the prime purpose of C++ being an object-oriented programming language.

Syntax

delete pointerVariable;

 

Example

#include <bits/stdc++.h>
using namespace std;

int main () {
  int* x  = NULL; // initialised with null
  x  = new int;   // Request memory for the variable

  *x = 12;     // Store value at allocated address
  cout << "Value of X : " << *x << endl;

  delete x;         // free up the memory.

  return 0;
}

 

Output

Value of X : 12

 

Explanation

In the above example, we have first created a pointer named ‘x’ and initialized it with null. Then using the ‘new’ operator, we have requested memory for the variable, and after that, we have assigned it the value ‘12’. Once the variable is used and is no longer required, we de-allocate the memory, which was allocated by ‘x’.

Try and compile with online c++ compiler.

Dynamic Memory Allocation for Arrays

Just like variables, we can also allocate memory for arrays dynamically using the below syntax. 

To create and allocate an array

Syntax 

int* pointer_variable=new int[size]; 

To de-allocate and remove the array

Syntax 

delete [] pointer_variable;

 

Example

#include <bits/stdc++.h>
using namespace std;

int main () {

  int* x  = new int[5]; // allocate memory with size as 5
  for(int i=1;i<=5;i++){
      x[i-1]=i; // intialize
  }
    for(int i=0;i<5;i++){
      cout<<x[i]<<" "; // use
  }
  delete [] x;         // free up the memory.
  return 0;
}

 

Output

1 2 3 4 5 

 

Explanation

In the above example, we have first dynamically allocated memory for 5 integers continuously, and then we have returned a pointer to the first element of the sequence, which is assigned to x. 

The major difference between declaring an array normally and declaring an array dynamically is that normal arrays are de-allocated by the compiler automatically, usually when the function containing the array returns or completes. Whereas the dynamically allocated array remains there until they are de-allocated by the programmer or program terminates.

Dynamic Memory Allocation for Objects

Objects are the same as variables of simple data types. We can dynamically create and allocate memory for objects in C++ using the ‘new’ operator, and similarly, we can de-allocate the memory of the objects using ‘delete’ operator.

Example

#include <bits/stdc++.h>
using namespace std;

class Plane {
  public:
      Plane() { 
        cout << "Constructor called" <<endl; 
      }
      ~Plane() { 
        cout << "Destructor called" <<endl; 
      }
};
int main() {
  Plane* obj = new Plane[2];
  delete [] obj; // Delete array

  return 0;
}

 

Output

Constructor called
Constructor called
Destructor called
Destructor called

 

Explanation

In the above example, first created we created an object array of size 2 using the new operator, as a result of which the constructor of the class is called 2 times, and similarly, when we de-allocate the memory occupied by the object, it calls the destructor 2 times too.

Must Read Dynamic Binding in C++

Frequently Asked Questions

Ques: What is the difference between malloc() and new operator?

Ans: Few of the differences between malloc() and new operator which are used to allocate dynamic memory are as follows:

  • The new operator calls the constructor, whereas malloc() doesn't.
  • In the case of the new operator, the compiler calculates the required size of memory, whereas, in the case of malloc(), the programmer has to manually calculate the size of memory.
  • The new operator returns the exact data type, whereas malloc() returns void.

Ques: What is the difference between free() and delete operator?

Ans: The main difference between free() and delete operator is that free() only de-allocates the memory without calling the destructor of the class, whereas the delete operator not only de-allocates the memory but also calls the destructor of the class.

Ques: Which memory is used when we dynamically store a variable/array/object in C++?

Ans: The heap memory is used when we dynamically store a variable/array/object in C++.

Key Takeaways

In this blog, we have covered the following things:

  • First, we discussed what dynamic memory allocation in C++ is.
  • Then we discussed how we could dynamically allocate memory for variables, arrays, and objects in C++ with examples.

In C++, we use a new and delete operator to perform dynamic memory allocation, similarly, we have malloc() and free() functions too in C++. To study about it more, refer to this. In dynamic memory allocation, we use pointers and use the concepts of references to understand and read about it more refer this.

Live masterclass