Home Icon Home Resource Centre Dynamic Memory Allocation In C++ Explained In Detail (With Examples)

Dynamic Memory Allocation In C++ Explained In Detail (With Examples)

Master the technical aspects of dynamic memory allocation in C++. Learn the syntax and techniques to manage memory dynamically, optimizing your code for efficiency and robust performance.
Shivani Goyal
Schedule Icon 0 min read
Dynamic Memory Allocation In C++ Explained In Detail (With Examples)
Schedule Icon 0 min read

Table of content: 

  • What Is Memory Allocation In C++?
  • The “new" Operator In C++
  • The "delete" Operator In C++
  • Dynamic Memory Allocation In C++ | Arrays
  • Dynamic Memory Allocation In C++ | Objects
  • Deallocation Of Dynamic Memory
  • Dynamic Memory Allocation In C++ | Uses
  • Conclusion
  • Frequently Asked Questions
expand icon

In the C++ programming language, we can allocate the memory to an array or variable at some point during the run time. This is what we mean by dynamic memory allocation. In other words, dynamic memory allocation & de-allocation is the process of allocating or de-allocating a block of memory in the course of the execution of a program/ software. In this article, we will discuss ways to carry out dynamic allocation in C++ i.e. new and delete operators, allocation ways for arrays, allocation of objects, and so on.

What is Memory Allocation in C++?

Memory allocation is basically a way of booking a partial or entire part of system memory space for the execution of applications. Memory allocation may be executed through a method known as memory management.

There are two types of memory spaces in our device- static memory and dynamic memory.

  1. Static Memory: In static memory allocation, memory is allotted and deallocated by the compiler on its very own. It's miles of permanent space allotted through the operating system which speeds up the time of execution of a program. We want to outline the required size of memory and it cannot reallocate the memory storage space consumed by means of the program until its execution is over.
  2. Dynamic Memory: In dynamic allocation, the allocation and deallocation of the memory happen at runtime. That is, the memory must be allocated or de-allocated by the program all through the run-time of a C++ program. So the programmer is required to deallocate the dynamically allocated memory which is not in use.

types of memory allocation in cpp

Difference Between Dynamic Allocation & Memory Allocated To Normal Variables?

In the case of static memory allocation for variables and arrays, the syntax is as follows:

int r;

double arr[10];

char name[20];

In this kind of memory allocation, the operating system automatically allocates the memory at compile time and de-allocates it when the program, block, or function finishes.

In comparison, in the case of dynamic memory allocation in cpp, the programmer must first create the dynamic space in the heap memory. Here, heap memory refers to the unused memory space available for dynamic allocation for a program, at runtime. They then allocate and de-allocate the memory. This is how the memory is dynamically allocated in C++, for variables and arrays, and an example of this is-

int* ptr = new int;

int* arr = new int[6];

Dynamically allocated memory will continue to be in use until the whole code or program terminates. So, a programmer needs to deallocate the memory, when it is not required. The need for this arises because memory leaks can occur when a programmer fails to de-allocate a dynamically allocated memory.

Also read- History Of C++ | Detailed Explanation (With Timeline Infographic)

Dynamic Memory Allocation In C++ Explained In Detail (With Examples)

The “new" Operator In C++

The new operator is a unary operator used to dynamically allocate a block of memory and keep its address in a pointer variable at some point during the execution of a program. In other words, this operator is like a request for memory allocation on the heap memory (or the free store). And if sufficient memory is available, the dynamic space is initialized to the newly created variable or pointer.

Syntax to use the new operator

pointer_variable = new data_type;

Here, pointer_variable indicates the pointer of type data_type. The new operator thus allocates a block of memory to type data_type. Note that the data_type here could either be any built-in data type (like an array) or a user-defined data type (like class, or structure).

How to allocation memory dynamically in C++? The new operator syntax

Example to C++ program to apply the new operator

*var=new int;

Program


          #include

using namespace std;

int main(){

int* Var;

Var = new int;

*Var = 50;

cout<<*Var;

}
      

Output

50

Explanation

Here we have dynamically allocated a block of memory using the new operator, for the int variable. Within this, we have allocated the memory in heap by using the Var pointer. The new operator returns the address of the memory location.

In the case of an array, the new operator returns the address of the first element of the array. From the above example, we can see the syntax for using the new operator.

What happens when there isn't enough space for the allocation of memory? 

The new keyword in C++ will throw an exception of type std::bad_alloc when there is insufficient memory available for dynamic memory allocation. The program segment won't receive a valid pointer to the requested memory block and as a result, the block of memory fails allocation, as indicated by this signal. In this case, the program should be terminated or the user should see an error message if developers notice this exception and handle the failure event appropriately.

You might also be interested in reading- Strings In C++ | Functions, How To Convert & More (With Examples)

The "delete" Operator In C++

What happens once we do not need the variable that we've got declared dynamically? Well, we must deallocate the space in memory occupied by means of the variable.

For this, we use the delete operator and de-allocate the block of memory, that was dynamically allotted with the use of the new operator. In view of that, a programmer must de-allocate a block of memory, as soon as it is not required within the program or code or it will lead to memory leaks. So, we require to use the delete operator to avoid memory leaks.

Syntax to apply the delete operator

delete pointer_variable;

Example to apply the delete operator

delete Var;

Program to use the delete operator:


          #include

using namespace std;

int main(){

int* Var;

Var = new int;

*Var = 50;

cout<<*Var;

delete Var;

}
      

Explanation

As you can see in the code above, we have dynamically allocated the memory for the int variable, by using the Var pointer. So after printing the contents of Var, we free the memory with delete.

Dynamic Memory Allocation In C++ Explained In Detail (With Examples)

Dynamic Memory Allocation In C++ | Arrays

Generally, we aren't sure of the exact size/ length of an array till runtime. And this is where dynamic memory allocation makes memory management extra efficient. Say you want to allocate memory for an array of integers, that is, an array of n integers. The syntax and example for getting this done are given below:

Syntax

pointer_variable = new data_type[size];

Example

str = new int[n]

Dynamic memory allocation in C++ for single dimension arrays

This was the syntax for normal arrays, now let's look at the syntax for multidimensional arrays. Note that in the syntax and example, we use the square brackets after the data_type to indicate that we are dynamically allocating for an array.

Syntax for a multidimensional array of length m x n,

pointer_variable = new data_type[size][size];

Example

var = new int [m][n];

Dynamic memory allocation in C++ for multidimension arrays

While the syntax to allocate the memory is different for a single element/ single dimension array and the multi-dimensional array, it remains the same for the deallocation process.

Syntax

delete []pointer_variable ;

Example

delete []var; // Delete array pointed to by means of var

Program to initialize dynamically allocated arrays:


          #include 

using namespace std;

int main(void) {

int num;

int *array{ new int[6]{ 1,2,3,4,5,6} };

cout << "Array elements: " << endl;

for (num = 0; num < 6; num++) {

cout << array[num] << endl;

}

return 0;

}
      

Output

Array elements:
1
2
3
4
5
6

Explanation:

  1. We first include the iostream header file in our program.
  2. Include the std namespace in our program so you can use its classes without calling it.
  3. Call the main() function. The program logic should be added to the function body.
  4. Declare an integer variable named x.
  5. Declare a dynamic array with an array name using an initializer list. This integer array will contain 5 integer elements. Note that we didn't use the "=" operator between the field length and the initializer list.
  6. Print some text to the console. Endl is a C++ keyword that means the end of the line and it brings the cursor to the next sentence.
  7. Use a for loop to iterate over the elements of an array.
  8. Print the contents of the field named field to the console.
  9. End of the for loop.
  10. The program must return a value.
  11. End of the main() function body.

Now let's look at an example that shows how to deallocate memory to arrays in C++.

Program to delete dynamic array memory:


          #include 

using namespace std;

int main() {

int length;

cin >> length;

int * array= new int[length];

for (int i = 0; i < length; i++) {

array[i] = (i + 1) * 10;

}

for (int i = 0; i < length; i++) {

cout << array[i] << " " << endl;

}

delete[] arr;

return 0;

}
      

Output

3
10
20
30

Explanation:

An array of integers is created by this C++ program, and each element is printed out. Prior to creating the array, we use the new operator and assign the array pointer to a variable. It first reads the length of the array from standard input. The array is then filled with values that are multiples of 10, rising by 10 for each entry starting at 10. Finally, we use the pointer notation and for loop to print out each element of the array. Then the delete[] operator is used to deallocate the memory that the array was occupying.

Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions

Dynamic Memory Allocation In C++ | Objects

It is also possible to dynamically allocate memory to objects. To begin with, the default constructor function initializes the object of class. And once the job is done, a default destructor function which is also a class member function deallocates the memory.  Let us look at an example wherein we are going to use an array of objects to make the concept clear.

Example of dynamic memory allocation for objects


          # include

using namespace std;

class tests {

public:

tests() {

cout<<"hello"<<endl;

}

~tests(){

cout<<"hey"<<endl;

}

};




int main() {

tests*t = new tests[3];

delete [] t;

return 0;

}
      

Output:

hello
hello
hello
hey
hey
hey

Explanation

Observe that given that we allotted an array of three test objects, the default constructor is called on thrice. In addition, while freeing these objects, the destructor is also called on three times.

Dynamic memory allocation in C++ for objects

Deallocation Of Dynamic Memory

Deallocation of memory may be carried out with the use of delete operators. The delete operator is used to deallocate, that is, it releases the memory which is turned into allotted through the new operator via its pointer ptr. The memory is then released in order that it can be used by a few different objects and no memory leak can arise.

Syntax

delete pointer_variable;

Example

delete ptr;

Program


          #include

using namespace std;

int main(){

int* Var;

Var = new int;

*Var = 50;

cout<<*Var;

delete Var;

}
      

Explanation

Here we use the Var pointer for the dynamic allocation of memory blocks, for the int variable. Then after printing the contents of Var, we free/ de-allocate memory blocks with the delete operator. 

Malloc Function, Calloc Function & Free Function

The C language makes use of the malloc() function and calloc() function to allocate memory dynamically at run time. These are both C standard library functions. It then makes use of a free() function to free dynamically allocated memory. While C++ also supports these features, the use of operators new and delete, carry out the task of allocating and releasing the memory in a better, less complicated, and more efficient manner.

Dynamic Memory Allocation In C++ | Uses

Using dynamically allocated memory is to allocate memory of variable length, which is not possible with compiler-allocated memory besides for variable-duration arrays.

  1. The amount of freedom and liberty programmers get with a dynamic allocation is one of the important uses. It makes it possible for users to allocate and deallocate memory as and when they need to.
  2. Dynamic memory allocation in C++ is also possible with the help of C standard library functions malloc() and calloc(), and deallocation with functions loose() and unfastened(). This can have its own benefits. 
  3. Since dynamic memory allocation happens at runtime, it makes it possible to efficiently allocate memory even when we don't know the variable size in advance. This also allows for allocation to varying sizes without any issues.
  4. The use of dynamic memory allocation is especially beneficial in special cases like trees, hyperlink-listing, and many others.

Conclusion

In C++, there are important ways to dynamically allocate memory i.e. with the use of the new operator and the delete operator. A memory block is allocated using the new operator and de-allocated using the delete operator. And for C-style functions malloc and free functions are used. We also saw examples of how dynamic memory allocation is done for arrays and objects.  Dynamic memory allocation in C++ is an essential concept in the discipline of data systems which includes related lists, stacks, queues, trees, etc.

Frequently Asked Questions

Q. What is dynamic memory allocation in CPP?

Dynamic memory allocation in C++ is a manner to allocate memory at some stage in program execution, instead of at compile time. It permits this system to request memory from the running device at runtime, after which it releases that memory when it is not in use. Dynamic memory allocation is typically used when the exact size of the data to be stored is not known at compile time, or when the size may change during program execution.

Using new and delete, you can allocate and deallocate memory for single objects or arrays of objects, while malloc and free can be used to allocate and deallocate blocks of memory of a particular length. 

It is critical to note that with dynamic memory allocation, it is the programmer's responsibility to control the memory efficiently. In this, it is critical to deallocate memory to avoid the possibility of memory leaks. This may be achieved by calling delete or free on the pointer returned with the aid of the memory allocation function, once the memory is not wanted.

Q. How many types of dynamic memory allocation are there in C++?

Dynamic memory allocation is a critical idea in C++ programming, as it allows developers to allocate memory at runtime, rather than during the compile time. In C++, there are two fundamental forms of dynamic memory allocation: using the "new" keyword and the usage of the "malloc" function.

The usage of the "new" keyword

The "new" keyword is used to allocate memory dynamically in the course of runtime. It is used to allocate a single item or an array of items on the heap memory. The syntax for using the "new" is as follows:

data_type *pointer_name = new data_type;

This syntax pronounces a pointer variable of the specified facts type and allocates memory on the heap to store the object of that data type. The "new" keyword returns a pointer to the allocated memory block, which is then assigned to the pointer variable.

Example:


          #include 

Using namespace std;

int main() {

int *q; // declare a pointer variable

q = new int; // allocate memory for a single integer on the heap

*q = 2; // store a value in the allocated memory block

cout << *q << endl; // output the value stored in the memory block

delete q; // release the memory back to the operating system

return 0;

}
      

The usage of the "malloc()" function

The "malloc" feature is borrowed from C programming and is used to allocate memory dynamically for the duration of runtime. It is used to allocate a block of memory of a unique length on the heap. The syntax for using the "malloc" function is as follows:

pointer_name = (data_type*) malloc(num_bytes);

This syntax proclaims a pointer variable of the specified datatype and allocates a block of memory on the heap of "num_bytes” size. The "malloc" function returns a pointer to the primary bytes of memory (allocated memory block), which is then assigned to the pointer variable. Observe that we need to cast the pointer to the right datatype.

Example:


          #include

#include 

use namespace std;




int main() {

int *q; // declare a pointer variable

q = (int*) malloc(sizeof(int)); // allocate memory for a single integer on the heap

*q = 2; // store a value in the allocated memory block

cout << *q << endl; // output the value stored in the memory block

free(q); // release the memory back to the operating system

return 0;

}
      

Q. What is the syntax to allocate memory in C++?

In C++, you can dynamically allocate memory using the "new" keyword, which returns a pointer to the new memory. The syntax for dynamically allocating memory in C++ is as follows:

datatype * pointer = new datatype;

Where "datatype" is the data type variable to allocate memory and "pointer" is the name of the pointer to which the new memory is allocated. The above syntax allocates memory for a variable of type "data type".

If you want to allocate memory for a different array, you can use the following syntax:

datatype * pointer = new datatype[num_elements];

where "element_num" is the number of elements in the array. The above syntax allocates memory for the variable array 'num_elements' of type 'datatype'.

When you have finished using the dynamically allocated memory, you must free it using the "delete" keyword as follows:

delete pointer;

or

delete[] pointer;

Or the variable array allocates memory. This frees up memory and frees it for other uses.

Q. What is dynamic RAM with an example?

Dynamic Random Access Memory (DRAM) is a type of computer memory that is commonly used in modern devices like pc, mobile, and gaming consoles. DRAM is risky, which means that it requires a constant delivery of power to preserve the stored records.

DRAM is made up of cells that consist of memory, each of which stores a bit of data as an electrical charge on a capacitor. The charge on the capacitor is refreshed regularly by a circuit within the DRAM chip to maintain the data's integrity.

An instance of DRAM in a computer gadget is the primary memory or RAM that stores records briefly at the same time as the computer is strolling. When you open a utility or file on your pc, the record is loaded from the hard drive or solid-state drive (SSD) into the DRAM, wherein it can be accessed quickly by means of the CPU. The more DRAM a system has, the more information it can store in memory, which ultimately enhances the system's average overall performance.

Q. Can you use smart pointers to dynamically allocate memory?

Yes, smart pointers are a C++ language feature that can be used to dynamically allocate memory on the heap. Smart pointers are a form of RAII (Resource Acquisition Is Initialization) item that robotically manages the life of the dynamically allocated memory. This allows you to save memory leaks and dangling pointers that may occur when memory isn't well managed.

There are three types of smart pointers in C++:

  1. unique_ptr: This smart pointer gives extraordinary possession of the dynamically allocated memory. One unique_ptr can only point to a given object at a time, and whilst the unique_ptr is destroyed, it routinely releases the memory it owns.
  2. shared_ptr: This smart pointer allows more than one pointer to share ownership of the dynamically allocated memory. The memory is robotically released when the last shared_ptr pointing to its miles is destroyed.
  3. weak_ptr: This smart pointer is used in conjunction with shared_ptr to break circular references. It provides a non-owning reference to the shared_ptr object and can be used to check if the object still exists.

You might also be interested in reading the following:

  1. Difference Between C And C++| Features | Application & More!
  2. C++ Interview Questions- The Basics, Uses, And More!
  3. Find In Strings C++ | Examples To Find Substrings, Character & More!
  4. Ways To Find String Length In C++ Simplified (With Examples)
  5. Typedef In C++ | Syntax, Application & How To Use It (With Examples)
Edited by
Shivani Goyal
Manager, Content

An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.

Comments

Add comment
No comments Image No comments added Add comment
Powered By Unstop Logo
Best Viewed in Chrome, Opera, Mozilla, EDGE & Safari. Copyright © 2024 FLIVE Consulting Pvt Ltd - All rights reserved.