Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Memory Leak Prevention in C++

Prevent memory leaks in C++ with a Resource class that frees memory in its destructor and follows the Rule of Three with a deep copy and safe assignment.

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}

Sample Output

Resource copied (deep copy)

The copy constructor ran for res2.

Resource freed

Printed once for each object.

In this one

  • What a memory leak is and how RAII prevents it
  • Why a raw pointer member needs a deep copy constructor
  • Why copy assignment must check for self-assignment
  • The Rules of Three, Five, and Zero

How it works

  1. 1

    res1 allocates 10 ints in its constructor.

  2. 2

    Resource res2 = res1 runs the copy constructor (deep copy).

  3. 3

    Both display size 10.

  4. 4

    At the closing brace, res2 then res1 are destroyed, each freeing its own block.

  5. 5

    The final message prints.

Edge cases

No copy constructor

Delete the custom copy constructor.

The default one copies the pointer, so res1 and res2 share data and both destructors delete[] it: a double free.

Self-assignment without the check

Remove if (this != &other) and do res1 = res1;

The object deletes its own data, then copies from the freed block, which is undefined behavior.

What's going on

A memory leak happens when memory from new is never given back with delete. This program prevents leaks by putting the new and the delete inside one class, so the object itself is responsible for its memory. That idea is called RAII: resource acquisition is initialization. Get the resource in the constructor, release it in the destructor.

Resource(int s) allocates size ints with new int[size] and prints a message.

~Resource() frees them with delete[] data. Because destructors run automatically when an object goes out of scope, you cannot forget this step. Setting data = nullptr inside the destructor is harmless but not needed; the object is about to disappear anyway.

Now the tricky part: copying. If the class did nothing special, copying a Resource would copy the pointer data, not the ints. Two objects would point to one block, and when both destructors ran, the block would be deleted twice. That is a double free, and it is undefined behavior.

So the class writes its own copy constructor. Resource(const Resource& other) allocates a new block of the same size and copies each int. That is a deep copy: each object owns its own memory.

The copy assignment operator handles a = b; between two existing objects. It checks this != &other first, because assigning an object to itself would otherwise delete its own data and then try to copy from the deleted block. Then it frees the old block, allocates a new one, copies, and returns *this so chains like a = b = c work.

Destructor, copy constructor, copy assignment: when a class needs one of them, it almost always needs all three. That is the Rule of Three. (C++11 adds move operations, making it the Rule of Five.)

In main, the inner braces create a scope. res1 allocates. Resource res2 = res1; is initialization, so the copy constructor runs, not assignment. At the closing brace both objects are destroyed in reverse order, res2 then res1, and "Resource freed" prints twice. Then the final message prints.

One small detail: the copy constructor copies other.data[i], but those ints were never set, so the copy is of garbage values. It does not matter here because nothing reads them, but in real code you would initialize the array, for example with new int[size]().

The easiest leak prevention is to not write new at all: a vector<int> member gives you correct copying, assignment, and cleanup with zero extra code. That is sometimes called the Rule of Zero.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which line triggers the copy constructor?

Pick an answer to check it.

Question 2

Destruction order at the closing brace?

Pick an answer to check it.

Questions people ask

Why is res2 = res1 here a copy constructor and not assignment?

Because res2 is being created on that line. Assignment only happens between two objects that already exist.

Do I still need this with vector?

No. A vector member handles copying and freeing itself.

How do I find leaks?

Tools like Valgrind or AddressSanitizer (-fsanitize=address) report them.