| by Arround The Web | No comments

Dynamic Memory Allocation in C++

Memory allocation is determined at the time of variable declaration. But in most cases, we don’t know how much memory is required for a specific variable. In that case, memory allocation has to be done on the runtime. The runtime memory allocation of the program is known as dynamic memory allocation. In dynamic memory allocation, we don’t know the actual size of the variable. We manually allocate the memory for that variable, and it can also be an array or object of a class. Pointers play a key role in dynamic memory allocation. When we dynamically allocate the memory, the “new” keyword is used to tell the compiler that we are dynamically allocating the memory. When we are done with allocating the memory, in the end, we need to manually “delete” that reserved dynamic memory. In other programming languages like Python and Java, we don’t have to dynamically allocate the memory because the compiler automatically does that. But in C and C++, we do this manually using the new (to reserve space) and delete (to free space) keywords.

Why Do We Dynamically Allocate the Memory?

In C++, dynamic memory allocation is done when we don’t know the actual size of the variable or items that we want to store in a variable. The total values that need to be stored are decided on the runtime. Heap allocates the dynamic memory but in the case of static, the memory is assigned in a stack. So, when we don’t know the exact size of variables and it has to be done on runtime, allocate the memory dynamically.

Syntax:

Reserve Memory

Pointer_Variable = new Data_Type;

First, we have to reserve the memory in a heap. For that purpose, we define a pointer type variable equal to the “new” keyword and then define the type of variable. The “new” keyword reserves the memory in the heap.

We can also define an array-type variable.

Pointer_Variable = new Data_Type[size];

To initialize the variable, we just put the value in the parenthesis after the Data_type() like this:

Pointer_Variable = new Data_Type(Value);

Free Memory

delete Pointer_Variable;

When we are done with the dynamic memory allocation, deallocate the memory to save the data from memory leakage. The “delete” keyword with the pointer variable name releases the dynamic memory.

Dynamic Memory Allocation of Variable

Let’s explain the allocation and deallocation process of the dynamic memory of an integer-type variable.

Code:

#include <iostream>

using namespace std;
int main () {
   int* p_value  = NULL;
p_value  = new int;  
   *p_value = 674;    
cout<< "Value of p_valueis : " << *p_value<<endl;
   delete p_value;

   return 0;
}

Start this code by including the header file to access the input and output methods of <iostream> library. This library has built-in methods that we can access in our program. Now, call the main() method and define a pointer variable “*p_value” to hold the heap address since the dynamic memory allocation is done in the heap. The static allocation is done in the stack because we already know that the amount of data means the size of the variable. Initialize the integer pointer with “NULL”.

Next, allocate the pointer “p_value” variable’s dynamic memory with the “new” keyword and the “int” data type of the variable. By using the term “new”, the compiler is instructed to allocate heap memory for the integer type variable. Additionally, store a value of “674” in the pointer type “*p_value” variable. Then, run the “cout” command to print the “Value of p_value” line and the value of integer “*p_value” variable that is dynamically stored in the heap. To retrieve the data that is saved in the heap, we use the pointer. The pointer stores and accesses the data in the heap; it does not directly access the data. Then, use the “delete” command to delete the pointer type “p_value” variable so that we don’t lose our data or no other person can access our data.

Output:

Value of p_value is : 674

Dynamic Memory Allocation of a Class Object

Let’s define a class and dynamically allocate the memory to its objects in this illustration.

Code:

#include <iostream>

using namespace std;
class Program_0 {
   public:
      Program_0() {
cout<< "I am Constructor" <<endl;
      }
      ~Program_0() {
cout<< "I am Destructor" <<endl;
      }
};
int main() {
   Program_0* myArray = new Program_0[3];
   delete [] myArray;
   return 0;
}

In this code, integrate the library to use the “cout” method. Then, use the standard namespace. Define a “Program_0” class and set this class as public. The public class methods can be accessed outside the class. The other classes can also access the methods of this class. Define the constructor and destructor within this class. We initialize the data members of the class in the constructor. The destructor destroys the objects once the program is executed. It frees the memory after the task is done. They both are defined by the class name.

In the Program_0() constructor, we write one line of code to print a message on the terminal. Similarly, in the ~Program_0() destructor, display a message by running the “cout” statement. Whenever the class object is created, the constructors and destructors are called. When we call the particular class, it executes the constructor and then performs other operations that we assign to it. After finishing the process, the destructor is called and it destroys all the objects that are created to access the class methods and data members.

Moreover, run the main() function of this code. Each class is called and its objects are created within this method. Create a pointer type “*myArray” object of the “Program_0” class and allocate the dynamic memory to it using the “new” keyword. Here, we define the size of array 3. The class is called three times, and the constructor also executes three times. After all this, the destructor is called three times to free up the space. The destructor deletes the object which calls the class thrice.

Output:

I am Constructor

I am Constructor

I am Constructor

I am Destructor

I am Destructor

I am Destructor

Conclusion

This document analyses the dynamic memory allocation in C++. We also observe why we dynamically allocate the memory. Dynamic memory allocation is important when we don’t know the actual size of the data to be stored. In other languages like Python, programmers do not need to manually allocate the memory because the compiler does it automatically. After allocating memory, storing the data there, and providing an access to it, the memory is deallocated. Deallocation is important because if we don’t deallocate the memory, there is a chance of memory leakage. The dynamic memory allocation of an integer variable and a class object is explained in the codes of this guide.

Share Button

Source: linuxhint.com

Leave a Reply