Introduction to C++ | Memory Management

C++ Memory Management

Memory management in C++ refers to the process of managing the allocation, use, and release of memory in a program. It is one of the key features of C++ because it allows developers fine-grained control over how memory is handled, unlike higher-level languages that use automatic memory management (e.g., garbage collection). Proper memory management is essential for creating efficient and error-free programs, especially in resource-constrained environments.

Types of Memory in C++

In C++, memory is divided into two main categories:

Allocating Memory Dynamically (Heap Memory)

C++ allows dynamic memory allocation using the new operator. The new operator allocates memory on the heap, and the programmer is responsible for freeing that memory using the delete operator.

Syntax for allocating memory dynamically using new:

Syntax for new


        pointer = new dataType; // Allocates memory for one element
        pointer = new dataType[size]; // Allocates memory for an array
                    

Example of Using new and delete

The following example demonstrates the use of new to allocate memory and delete to release the allocated memory:

Code Example: new and delete


        #include <iostream>
        using namespace std;
        
        int main() {
            // Dynamically allocate memory for an integer
            int* ptr = new int;
        
            // Assign a value to the allocated memory
            *ptr = 10;
            cout << "Value: " << *ptr << endl;
        
            // Free the allocated memory
            delete ptr;
        
            // Dynamically allocate memory for an array of integers
            int* arr = new int[5];
        
            // Assign values to the array
            for (int i = 0; i < 5; i++) {
                arr[i] = i * 2;
            }
        
            // Print array values
            for (int i = 0; i < 5; i++) {
                cout << "arr[" << i << "] = " << arr[i] << endl;
            }
        
            // Free the array memory
            delete[] arr;
        
            return 0;
        }
                    

Output

Value: 10
arr[0] = 0
arr[1] = 2
arr[2] = 4
arr[3] = 6
arr[4] = 8

Memory Leaks and How to Avoid Them

A memory leak occurs when memory is allocated but not properly deallocated. This can lead to wasted memory and potential program crashes over time. To avoid memory leaks:

Smart Pointers in C++

Smart pointers are wrappers around raw pointers that help manage memory automatically. They ensure that the memory is freed when the pointer goes out of scope, reducing the risk of memory leaks.

Example of Using Smart Pointers

Here’s an example demonstrating the use of std::unique_ptr to manage dynamically allocated memory:

Code Example: Using Smart Pointer


        #include <iostream>
        #include <memory>
        using namespace std;
        
        int main() {
            // Create a unique_ptr to manage memory
            unique_ptr ptr = make_unique();
        
            *ptr = 20;
            cout << "Value: " << *ptr << endl;
        
            // No need to manually delete; memory will be freed when ptr goes out of scope
            return 0;
        }
                    

Output

Value: 20

Pro Tip:

💡 Pro Tip

When using raw pointers for dynamic memory allocation, always ensure that delete or delete[] is called to release memory. Consider using smart pointers like std::unique_ptr and std::shared_ptr for automatic memory management to reduce the risk of memory leaks and improve code safety and readability.