In this blog we are going to discuss “How to find memory leak using valgrind memory debugging tool”. In previous blog  we have implemented trie data structure with insert and search operation. This implementation has some memory leak. Let us find memory leak using valgrind tool. Let us see below code.

How to find memory leak using valgrind memory debugging tool

  • compile above code using gcc -g  trie.c -o trie
  • And run using valgrind –tool=memcheck –leak-check=full ./trie , we will see output as

observation on valgrind output

  • From the above valgrind messages we can see that our program has memory leak.

==3863== LEAK SUMMARY:
==3863==    definitely lost: 216 bytes in 1 blocks
==3863==    indirectly lost: 648 bytes in 3 blocks

  • The stack trace tells where the leaked memory was allocated.Memcheck tool cannot tell why does memory leaks.

==3863==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/
==3863==    by 0x4005CE: makeNode (trie.c:14)
==3863==    by 0x40076C: main (trie.c:61)

  • Whenever a programmer allocate memory using malloc, it is programmer to delete memory using library function free().
  • So to delete memory allocated in our trie implementation we need to traverse entire trie and delete allocated memory.


Related Contents to follow