Memory Leak Prevention

Memory Leak Prevention and Best Practices in C++

IntermediateTopic: Memory Management Programs
Back

C++ Memory Leak Prevention Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

class Resource {
private:
    int* data;
    int size;

public:
    Resource(int s) {
        size = s;
        data = new int[size];
        cout << "Resource allocated: " << size << " integers" << endl;
    }
    
    // Destructor - prevents memory leak
    ~Resource() {
        if (data != nullptr) {
            delete[] data;
            data = nullptr;
            cout << "Resource freed" << endl;
        }
    }
    
    // Copy constructor - deep copy
    Resource(const Resource& other) {
        size = other.size;
        data = new int[size];
        for (int i = 0; i < size; i++) {
            data[i] = other.data[i];
        }
        cout << "Resource copied (deep copy)" << endl;
    }
    
    // Assignment operator - prevent double deletion
    Resource& operator=(const Resource& other) {
        if (this != &other) {  // Self-assignment check
            delete[] data;  // Free existing memory
            
            size = other.size;
            data = new int[size];
            for (int i = 0; i < size; i++) {
                data[i] = other.data[i];
            }
        }
        return *this;
    }
    
    void display() {
        cout << "Resource size: " << size << endl;
    }
};

int main() {
    {
        Resource res1(10);
        res1.display();
        
        // Copy constructor prevents shallow copy issues
        Resource res2 = res1;
        res2.display();
        
    }  // Destructors called automatically
    
    cout << "\nAll resources properly freed" << endl;
    
    return 0;
}
Output
Resource allocated: 10 integers
Resource size: 10
Resource copied (deep copy)
Resource size: 10
Resource freed
Resource freed

All resources properly freed

Understanding Memory Leak Prevention

Memory leaks occur when dynamically allocated memory is not freed. Prevention techniques: 1) Always match new with delete, 2) Use destructors to free resources, 3) Implement copy constructor and assignment operator (Rule of Three), 4) Use RAII (Resource Acquisition Is Initialization), 5) Set pointers to nullptr after deletion, 6) Use smart pointers (C++11+). This program demonstrates proper memory management.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Memory Leak Prevention

This C++ program is part of the "Memory Management Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents