1

I am trying to debug my program using valgrind to check for lost my memory and hope to fix a seg fault. Valgrind produced the below output, but when I checked the corresponding lines in the code, the line that valgrind pointed to was just creating a new object. Here is the part of the program that valgrind complains about:

relevant valgrind output:

--13598-- REDIR: 0x36fd4803d0 (free) redirected to 0x4a074f0 (free)
==13598== 
==13598== HEAP SUMMARY:
==13598==     in use at exit: 168 bytes in 1 blocks
==13598==   total heap usage: 31 allocs, 31 frees, 1,108 bytes allocated
==13598== 
==13598== Searching for pointers to 1 not-freed blocks
==13598== Checked 188,824 bytes
==13598== 
==13598== 168 bytes in 1 blocks are definitely lost in loss record 1 of 1
==13598==    at 0x4A06965: operator new(unsigned long) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==13598==    by 0x400F94: MLH<int>::MLH() (MLH.h:50)
==13598==    by 0x400C71: main (Benchmark.cpp:23)
==13598== 
==13598== LEAK SUMMARY:
==13598==    definitely lost: 168 bytes in 1 blocks
==13598==    indirectly lost: 0 bytes in 0 blocks
==13598==      possibly lost: 0 bytes in 0 blocks
==13598==    still reachable: 0 bytes in 0 blocks
==13598==         suppressed: 0 bytes in 0 blocks
==13598== 
==13598== ERROR SUMMARY: 7 errors from 5 contexts (suppressed: 2 from 2)

MLH.h:

template <typename T>
MLH<T>::MLH()
{
  proot = new HashNode<T>();
}

HashNode.h

template< typename T >
HashNode< T >::HashNode()
{
  for(int i=0; i<5; i++){
    keyArray[i] = -1;
    dataArray[i] = NULL;
    childArray[i] = NULL;
    //levelsArray[i] = 0;
  }
  for(int j = 0; j<9; j++ ){
    levelsArray[j] = 0;
  }
  levelsArray[0] = 1;
  numElements = 0;
  numChildren = 0;
  nodeLevel = 0;
  stemNode = 0;
  steps = 0;

  MLH_print_option = 0;
}

template <typename T>
MLH::~MLH()
{
    //delete proot
    for (int i=0; i< 5; i++) {
        if(proot->childArray[i] != NULL){
            delete proot->childArray[i];
        }
    }
}

I see that the problem is being called when I try to initialize the HashNode object, but this does not make sense to me. Is there something I'm not seeing?

Edward
  • 6,964
  • 2
  • 29
  • 55
Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59

1 Answers1

1
template <typename T>
MLH::~MLH()
{
    //delete proot
    for (int i=0; i< 5; i++) {
        if(proot->childArray[i] != NULL){
            delete proot->childArray[i];
        }
    }
}

I see a number of problems with the above:

  • You are deleting the elements of proot->childArray but you are not deleting proot itself. This is your leak.
  • There's no need for that test for null. Just delete it. Applying delete to a null pointer does nothing.
  • Why is this function in the file HashNode.h?
David Hammen
  • 32,454
  • 9
  • 60
  • 108