views:

376

answers:

1

I'm running valgrind 3.5.0 to try and squash memory leaks in my program. I invoke it as so:

valgrind --tool=memcheck --leak-check=yes --show-reachable=yes

After my program finishes valgrind reports that

==22926==
==22926== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 17 from 1)
==22926== malloc/free: in use at exit: 20,862 bytes in 425 blocks.
==22926== malloc/free: 25,361 allocs, 24,936 frees, 772,998 bytes allocated.
==22926== For counts of detected errors, rerun with: -v
==22926== searching for pointers to 425 not-freed blocks.
==22926== checked 91,884 bytes.

Despite telling me that there are 0 errors I'm concerned that the number of allocations and frees do not match. More worrisome still is the following:

==22926== LEAK SUMMARY:
==22926==    definitely lost: 68 bytes in 1 blocks.
==22926==    indirectly lost: 20,794 bytes in 424 blocks.
==22926==      possibly lost: 0 bytes in 0 blocks.
==22926==    still reachable: 0 bytes in 0 blocks.
==22926==         suppressed: 0 bytes in 0 blocks.

There is additional output, pertaining to what appears to be a leak:

==22926== 20,862 (68 direct, 20,794 indirect) bytes in 1 blocks are definitely lost in loss record 9 of 17
==22926==    at 0x40269EE: operator new(unsigned int) (vg_replace_malloc.c:224)
==22926==    by 0x807960B: OneTwoThree::OneTwoThree(Scenario const*) (onetwothree.cc:22)
==22926==    by 0x804DD69: main (scsolver.cpp:654)

At the line in question in the constructor of OneTwoThree I have the following:

OneTwoThree::OneTwoThree (const Scenario* scenario) :
    Choice("123", scenario, new Solution (scenario->name(), scenario)),
    seen_(new bool [sol_->numVisits()])
{
}

later, in the destructor, seen_ is deleted as so:

OneTwoThree::~OneTwoThree ()
{
    delete [] seen_;
}

There is no reallocation of memory associated with seen_; I only flip the bools to true/false during the course of running my program.

I can't see a leak here and I don't understand what valgrind is trying to tell me. I've been reading through the valgrind manual (specifically, this) but I'm not being enlightened much.

Can anyone help me grok this output?

+1  A: 

The commenters to the OP were spot on; The Solution object being created in the constructor was never being deleted. I've fixed the egregious oversight and gotten rid of the ugly code creating new objects outside of the constructor of the object which is responsible for them.

Thank you Artelius, Nikolai and Jonathan!

Daniel
Also, memory leaks may creep up in the assignment operator when holding resources. Follow the Law of the Big Three: whenever you write one of Copy Constructor, Assignment Operator or Destructor; write the other two as well. Personally, I think that the Assignment Operator is best written with the copy and swap idiom.
Matthieu M.