Memory Management in C++

Memory Management in C++

Managing memory is very crucial for stable and efficient C++ applications. Unlike Java, Python or Javascript which automatically identify and dispose of unused memory, making life easier for developers, C++ lack this capability. This is possible due to built-in garbage collectors reducing the risk of bugs and memory-related issues.
Memory leaks and segmentation faults are common pitfalls in C++ where developers must manually allocate and deallocate memory.

Following are the best practices/tools for avoiding memory-related issues in C++ :

  1. delete operator

  2. user-defined destructors

  3. smart pointers

Let's explore each of them with code examples.

  • delete operator

    A delete operator is used to deallocate memory space that is dynamically created using the new operator. Whenever a memory is created dynamically, it occupies space in the heap section which, unlike stack, cannot be freed automatically once the scope is over. The user needs to deallocate the heap forcefully.

#include <iostream>
using namespace std;

int main() {
    // Allocate memory for an integer in heap
    int *number = new int(25);

    // Use the allocated memory
    cout << "Value is : " << *number << endl;

    // Deallocate the memory to prevent memory leak before program ends
    delete number;
}
  • user-defined destructors

    A destructor works opposite to the constructor. It destroys the object once it goes out of scope or the program ends. If the object acquires resources in a heap memory then the user-defined destructor is a must to avoid memory leak.

#include <iostream>
using namespace std;

class Test {
private:
    int *number;

public:
    // User-Defined Default Constructor
    Test() { 
        // Allocating memory in heap
        number = new int(25);
     }

    // User-Defined Destructor
    ~Test() { 
        // Deallocating the heap memory
        delete number;
     }
};
main()
{
    // Object 't' will hold one integer variable in heap
    Test t;
    // Before the program ends, destructor is called
    // It is important to free heap resource held by object
}
  • smart pointers

    Smart pointer in C++ programming is an idea to compensate for the absence of garbage collectors. With Smart Pointers in C++, you can forget about the nightmare of running out of memory. It solves problems related to memory leaks, dangling pointers etc. It automatically frees up the heap resources held by objects even if the user forgets to do so manually. Always try to use smart pointers in place of raw pointers.

#include <iostream>
#include <memory>
// Include the memory header for smart pointers
using namespace std;

int main() {
    // Allocate memory for an integer in heap using smart pointer
    // unique pointer is a type of smart pointer
    unique_ptr<int> number = make_unique<int>(25);

    // Use the allocated memory
    cout << "Value is : " << *number << endl;
}
// No need to use delete operator 
// Memory is automatically freed once program ends

Note: There are three different types of smart pointers for different scenarios. Smart pointer is a big topic to cover over here.

In summary, a garbage collector automates memory management, offering ease and safety for developers. In contrast, languages without garbage collection require manual memory control, demanding careful attention to prevent memory-related issues.