Memory Leak Prevention in C++
Memory Leak Prevention and Best Practices in C++.
IntermediateMemory Management ProgramsExample 10 of 11
memory-leak-prevention.cpp
1#include <iostream>2using namespace std;34class Resource {5private:6 int* data;7 int size;89public:10 Resource(int s) {11 size = s;12 data = new int[size];13 cout << "Resource allocated: " << size << " integers" << endl;14 }1516 // Destructor - prevents memory leak17 ~Resource() {18 if (data != nullptr) {19 delete[] data;20 data = nullptr;21 cout << "Resource freed" << endl;22 }23 }2425 // Copy constructor - deep copy26 Resource(const Resource& other) {27 size = other.size;28 data = new int[size];29 for (int i = 0; i < size; i++) {30 data[i] = other.data[i];31 }32 cout << "Resource copied (deep copy)" << endl;33 }3435 // Assignment operator - prevent double deletion36 Resource& operator=(const Resource& other) {37 if (this != &other) { // Self-assignment check38 delete[] data; // Free existing memory3940 size = other.size;41 data = new int[size];42 for (int i = 0; i < size; i++) {43 data[i] = other.data[i];44 }45 }46 return *this;47 }4849 void display() {50 cout << "Resource size: " << size << endl;51 }52};5354int main() {55 {56 Resource res1(10);57 res1.display();5859 // Copy constructor prevents shallow copy issues60 Resource res2 = res1;61 res2.display();6263 } // Destructors called automatically6465 cout << "\nAll resources properly freed" << endl;6667 return 0;68}
Output
Resource allocated: 10 integers Resource size: 10 Resource copied (deep copy) Resource size: 10 Resource freed Resource freed All resources properly freed
What's going on
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+).