Tutorial Study Image

Memory Management in c++


November 8, 2022, Learn eTutorial
1193

Memory management in C++ is a method of controlling computer memory and allocating the necessary amount of memory for programs to execute. Since it shares the same fundamental idea as other programming languages, it is almost understandable. It deals with the allocation of space and memory in terms of improvisation for the functioning of the overall computer system. The use of arrays in memory management is essential because they enable the storage of data with suitable spacing alignment, the maintenance of timing constraints, and effective resource management through the use of the new keyword for memory allocation.

What do you mean by memory management in C++?

  • The process of managing computer memory involves allocating memory space to programs in order to enhance system performance.
  • In C++, we will be able to allocate memory for a variable or an array during runtime. This is mainly referred to as "dynamic memory allocation.
  • After we have finished using a variable, we must manually deallocate the memory that was dynamically allocated in C++.
  • Variable memory allocation is automatically managed by the compiler in other programming languages like Java and Python. However, C++ differs from this.

In C++, how does Memory Management work?

  • For any programming language, including C++, memory management is one of the cores and most essential concepts. The memory management concept overview relies mostly upon the time-space trade-off as well as the concept of memory allocation. Using arrays makes it easier to manage problems with memory and space. The primary part of, or one could say that supports, the memory management concept is the data structure known as an array. Arrays are the data structures that include all the data that is kept in memory by an effective allocation of resources with the proper time and space as it allocates memory at the time of array declaration and then has to use the new operator in order to allocate memory dynamically at the run-time to prevent memory wastage.
  • In some cases, even if the programmer declares an array with the maximum size and subsequently allocates the memory in accordance with the need, some memory space or cells may still be left unused. It is essential to remember that the memory allocation approach of defining an array using the new keyword, which will handle this kind of circumstance.
  • Any programmer must also consider how the program flow will be during the implementation as well as how the resources may effectively manage the time-space trade with regard to memory management. Even though the memory management operators are there to handle memory allocation during runtime, they should nevertheless exercise additional caution because doing so will prevent them from aiming for any form of memory allocation. 
  • C++ memory management uses the unary operators like new and delete for allocating memory and also for creating free space for allocating the resources efficiently. 
  • The memory operators in C++ memory management use the new and delete operators. Unlike the C programming language, which uses the malloc and calloc functions to dynamically allocate memory at runtime and the free() function to deallocate the dynamically allocated memory, C++ memory management uses the unary operators like new and delete, as discussed previously, to accomplish the same purpose of allocating memory and creating free space for the efficient allocation of resources.

What is the need for memory management?

  • Since arrays store homogeneous data, memory is typically allocated for an array at the time of declaration.
  • There are situations when it is impossible to know the precise memory until runtime.  We declare an array with maximum size to prevent this from happening, but some memory will remain unused.
  • By using the new operator to allocate memory dynamically at runtime, we can prevent memory wasting.

How is memory allocated as well as deallocated?

The malloc() and calloc() functions in C are used to allocate memory dynamically at run time, and the free() function is used to free the memory which is dynamically allocated.C++ includes these functions, as well as the two operators new and delete, which improve and simplify the operation of allocating as well as freeing the memory. Using the new and delete operators, we may dynamically allocate and subsequently deallocate the memory.

new and delete operators in C++

new operator  in C++

  • Memory is allocated to a variable using the new operator.
  • An allocation of memory on the Free Store is requested using the new operator.
  • If enough memory is available, the new operator initializes the memory and provides the location of the newly allocated and initialized memory to the pointer variable.

Syntax


pointer_variable = new data-type;
 
  • ptr var: This stands for the pointer variable's name.
  • new: the operator used to create the object for the allocation.
  • data tp: Identifies the type of data that was used during allocation.
     

The new operator is used to create the object using the abovementioned syntax. The name of the pointer variable is "pointer variable" in the syntax above, "new" is the operator, and "data-type" specifies the type of the data.

For example let us understand the code given below


//  an int pointer declaration
int* ptVar;

//  memory is allocated dynamically 
// the new keyword is used
ptVar = new int;

// assign value to allocated memory
*pttVar = 7;

 

Here, we've used the new operator to dynamically allot memory for an int variable.

You'll see that we allocated the memory dynamically by using the pointer ptVar. This is so because the new operator returns the memory location's address.

The new operator returns the address of the array's first element in the case of an array.

delete operator in C++

Since it is the job of the programmer to deallocate dynamically allocated memory, the C++ language provides the delete operator.
We can deallocate the memory used by a dynamically declared variable if we no longer require it.
The delete operator is used for this purpose. The operating system receives the memory back in this process. This is referred to as memory deallocation.

Syntax


delete ptr_var;
 
  • delete: This stands for the unary operator that should be called after the new operator is called.
  • ptr var: This is a pointer to the object formed mostly by the new unary operator mainly for further deletion.

For example, let us understand the code given below


//  int pointer declaration
int* ptVar;

// dynamically allocate the  memory for an int variable 
ptVar = new int;

//  value is  assigned to the variable memory
*ptVar = 9;

// print the value which is  stored in memory
cout << *ptVar; // Output: 9

// deallocate the memory
delete ptVar;
 

Example: let us write a C++ program to understand dynamic allocation as well as deallocation of the memory mainly by using the new and delete operators.


#include <iostream>
using namespace std;

int main() {
    //  int pointer is declared
    int* pInt;

    //  float pointer is  declared
    float* pFloat;

    //  allocate the  memory dynamically
    pInt = new int;
    pFloat = new float;

    // assigning value to the memory
    *pInt = 2f;
    *pFloat = 2.24f;

    cout << *pInt << endl;
    cout << *pFloat << endl;

    // deallocate the memory
    delete pInt, pFloat;

    return 0;
}

Output:

2
2.24

We used dynamic memory allocation in this program to create two int and float type variables. We assign values to them, print them, and then deallocate the deleted memory.