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;
3
4class Resource {
5private:
6 int* data;
7 int size;
8
9public:
10 Resource(int s) {
11 size = s;
12 data = new int[size];
13 cout << "Resource allocated: " << size << " integers" << endl;
14 }
15
16 // Destructor - prevents memory leak
17 ~Resource() {
18 if (data != nullptr) {
19 delete[] data;
20 data = nullptr;
21 cout << "Resource freed" << endl;
22 }
23 }
24
25 // Copy constructor - deep copy
26 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 }
34
35 // Assignment operator - prevent double deletion
36 Resource& operator=(const Resource& other) {
37 if (this != &other) { // Self-assignment check
38 delete[] data; // Free existing memory
39
40 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 }
48
49 void display() {
50 cout << "Resource size: " << size << endl;
51 }
52};
53
54int main() {
55 {
56 Resource res1(10);
57 res1.display();
58
59 // Copy constructor prevents shallow copy issues
60 Resource res2 = res1;
61 res2.display();
62
63 } // Destructors called automatically
64
65 cout << "\nAll resources properly freed" << endl;
66
67 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+).