O'Reilly logo

Mastering C++ Programming by Jeganathan Swaminathan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Fixing the memory leaks

Let's try to fix the memory leak issue by adding the following code in the List::~List() destructor:

List::~List( ) {        cout << "\nList destructor invoked ..." << endl;        Node *pTemp = NULL;        while ( pHead != NULL ) {                pTemp = pHead;                pHead = pHead->next;                delete pTemp;        }        pNewNode = pHead = pTail = pTemp = NULL;        __size = 0;}

From the following output, you will observe that the memory leak has been fixed:

g++ main.cpp list.cpp -std=c++17 -gvalgrind ./a.out --leak-check=full==44813== Memcheck, a memory error detector==44813== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.==44813== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info==44813== Command: ./a.out --leak-check=full==44813== List constructor ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required