Open In App

How to Release Memory in C++?

Last Updated : 04 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, releasing memory means deallocating the memory that was previously allocated by the user. It is very important to avoid memory leaks. Other programming languages like Java support automatic garbage collection to release the dynamically allocated memory, but in C++ we have to release the allocated memory manually. In this article, we will learn how to release memory in C++.

Free the Allocated Memory in C++

In C++, if the dynamic memory allocation is done using the new operator, we have to release the allocated memory using the delete operator manually. For arrays allocated with new[], the delete[] operator should be used.

Syntax to Release Memory in C++

//For single elements
delete object_name

//For arrays
delete[] arrayName;

Here, object_name can be a pointer or any other data object in C++.

Note: Remember to always deallocate any memory that you’ve dynamically allocated when you’re done using it otherwise that can lead to memory leaks and can eventually cause the system to run out of memory.

It is also important to note that we can also allocate memory in C++ using malloc() and calloc() (inherited from C language). This allocated memory should be freed by the function free().

C++ Program to Release Memory in C++

The following program illustrates how we can release memory for dynamically allocated array in C++.

C++
// C++ Program to  illustrate how we can release memory for
// dynamically allocated array
#include <iostream>
using namespace std;

int main()
{

    // Allocate memory for an array of size 5
    int* arr = new int[5];

    // use the array
    for (int i = 0; i < 5; i++) {
        arr[i] = i;
        cout << arr[i] << " ";
    }
    cout << endl;

    // Release the memory using delete
    delete[] arr;

    cout << "Memory for array released " << endl;
    // Set the pointer to nullptr to avoid dangling pointers
    arr = nullptr;
    return 0;
}

Output
0 1 2 3 4 
Memory for array released 

Time Complexity: O(1) where N is the size of the array.
Auxiliary Space: O(1)

We can also use smart pointers (like std::unique_ptr, std::shared_ptr, and std::weak_ptr) to manage dynamic memory that automatically release the memory when object goes out of scope, in order to prevent any memory leaks.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads