c++

C++ Memory Management

C++ allows us to allocate the memory of a variable or an array in run time. This is known as Dynamic Memory Allocation.But before understanding the term called Dynamic Memory Location let us understand the meaning of Dynamic .In programming the word Dynamic refers to run time.So the term Dynamic Memory Location means allocating memory at run time.On the other hand if you look at the other languages such as Java , Python the compiler automatically manages the memories allocated to variables. But this is not the case in C++.In C++, we need to deallocate the dynamically allocated memory manually after we have no use for the variable.We can allocate and then deallocate memory dynamically using operators called new and delete.


Types of Memory Allocation

  1. Compile time (Static) Memory Allocation.
  2. Run time (Dynamic) Memory Allocation.
  1. Compile time Memory Allocation:-If the compiler is able to determine the number of bytes required for a variable or array by looking at its declaration then we say that it is Static or Compile time Memory Location.

    For Example:1. int a; // this line clearly indicates that variable a will require 2 or 4 bytes.

    Example: 2. int arr[10]; // this line also clearly indicates that the array will require20 or 40 bytes.

    Thus both the above declaration are called Static Memory Location.

  2. Run time Memory AllocationIf the memory required by the variable or array is calculated at run time then such allocation is called as Dynamic Memory Allocation.We use the kind of memory allocation to create arrays of user defined size and these arrays are called as Dynamic Arrays.
memory mng.pic


Allocation of Heap Memory using New Keyword

Syntax:

Data_type pointername = new data_type


For example:

int *new_op = new int;  // allocating block of memory
int *new_op = new int[ 5 ];

If enough amount of memory is not available in heap so it is indicated by throwing an exception of type std::bad_alloc and a pointer is returned.


Deallocation of memory using Delete Keyword

Once heap memory is allocated to a variable or class object using the new keyword, we can deallocate that memory space using the delete keyword.It return the memory to the Operating System. This is Known as the Memory Deallocation.

Syntax:

delete pointervariable


Consider the code:

// declare an int pointer  
int* pointVar;
// dynamically allocate memory// for an int variable
pointVar = new int;
// assign value to the variable memory
*pointVar = 20;
// print the value stored in memory
cout << *pointVar; // Output: 20
// deallocate the memory
delete pointVar;

Here, we have dynamically allocated memory for an int variable using the pointer pointvar.After printing the contents of pointvar, we deallocated the memory using delete


Example 1: Dynamic Memory Allocation
#include <iostream>using namespace std;
int main()
{
// declare an int pointer
int* pointInt;
// declare a float pointer
float* pointFloat;
// dynamically allocate memory
pointInt = new int;
pointFloat = new float;
// assigning value to the memory
*pointInt = 20;
*pointFloat = 20.20f;
cout << *pointInt << endl;
cout << *pointFloat << endl;
// deallocate the memory
delete pointInt, pointFloat;
return 0;
}
Output
Output:
20
20.20

In this program, we dynamically allocated memory to two variables of int and float types. After allocting the values to them and printing them, we finally deallocate the memories using the code.

delete pointInt, pointFloat;

Note:Dynamic memory allocation can make memory management more efficient.Especially for arrays, where a lot of the times we don't know the size of the array until the run time.

Example 2: New and Delete Operator for Arrays
// C++ Program to store GPA of n number of students and display it// where n is the number of students entered by the user

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    int number;
    cout << "kindly enter total number of students: ";
    cin >> number;
    float* ptr;
// memory allocation of num number of floats
    ptr = new float[number];
    cout << "Kindly enter GPA of students." << endl;
    for (int i = 0; i < number; ++i) {
    cout << "Student" << i + 1 << ": ";
    cin >> *(ptr + i);
}
    cout << "\nShowing GPA of students." << endl;
    for (int i = 0; i < number; ++i) {
    cout << "Student" << i + 1 << " :" << *(ptr + i) << endl;
}
// ptr memory is released
    delete [] ptr;
    return 0;
}
Output:
Kindly enter total number of students: 10
Kindly enter GPA of students.
Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9
Student5: 3.0
Student6: 4.0
Student7: 3.3
Student8: 2.6
Student9: 3.5
Student10: 3.2
Showing GPA of students.
Student1 :3.6
Student2 :3.1
Student3 :3.9
Student4 :2.9
Student5 :3.0
Student6 :4.0
Student7 :3.3
Student8 :2.6
Student9 :3.5
Student10 :3.2

In the above program, we have asked from the user to enter the number of students and store it in the number variable.Then, we have allocated the memory dynamically for the float array using new.We enter data into the array (and later print them) using pointer notation.After we no longer need the array, we deallocate the array memory using the code delete [ ] ptr; .Notice the use of [ ] after delete. We use the square brackets [ ] in order to denote that the memory deallocation is that of an array.