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.

Table of Contents