Menu
Coddy logo textTech

Memory Leaks

Lesson 12 of 14 in Coddy's C++ Pointers course.

In the previous lesson, we used the delete keyword since it's really important to deallocate the memory that you have allocated. Now, we will learn about it in more detail.

A memory leak occurs when a program allocates memory from the heap but fails to deallocate it after it is no longer needed.

Essentially, when we run the program, we allocate the wanted memory and later we forget about it and that memory never gets deallocated/deleted. Look at the example below:

int *p, *q; // Declaration
p = new int; // Allocating
q = new int; // Allocating

*p = 10; // Setting
*q = 20; // Setting

cout << *p << " " << *q << endl;
q = p; // q and p point to the same location
// Initial location of q is LOST
cout << *p << " " << *q << endl;

delete p;
delete q;
Output:
10 20
10 10

At first, we declare the pointers, allocate memory for one integer each, and next, we set the values at those addresses, as you can see we can print them out on the first cout


Where things get interesting is on the <i>q = p</i> line, we set the pointer <i>q</i> to point at the same location where <i>p</i> is pointing, with that the initial location that we allocated for <i>q</i> to point to is lost permanently and can no longer be accessed or deleted.


As you can see in the following line we print out the dereferenced pointers again and we get equal values, because they point at the same location

This is why worrying about memory leaks and managing dynamically allocated data is so important.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Write the same program from the last lesson, but this time deallocate all of the memory allocated using the delete keyword. Dynamically allocate memory for three integers using the pointers ptrA, ptrB, and ptrC. Use the three integers given as the function's arguments and set the values at the pointer address to equal the integers respectively. First integer to ptrA, the second integer to ptrB , and the last integer to ptrC, and finally print out all of the pointers dereferenced and separated with a whitespace

Do NOT write the <i>main()</i> function

Try it yourself

#include <iostream>

using namespace std;

void dynamicMemory(int a, int b, int c) {
    // Enter your code here
    
    // Deallocate memory
}

// Do NOT write the main() function

All lessons in C++ Pointers