galvanize
galvanize

Reputation: 547

Mysterious memory leakage

I have code on the Internet which is not perfect written, however it seemed to me that there is no memory leakage. However to be sure I used valgrind who has different opinion.

Here is code:

class BaseClass {
public:
    virtual ~BaseClass() {}
};

class DerivedClass1 : public BaseClass {
};

class DerivedClass2 : public BaseClass {
};

class UserClass {
private:
    BaseClass* base_;
public:
    void setDerived(BaseClass* p_base) {
        delete base_;
        base_ = p_base;
    }

    UserClass (BaseClass *p_base){
        base_ = p_base;
    }

    ~UserClass() {
       delete base_;
    }
};

int main() {
    UserClass * my_class = new UserClass(new DerivedClass1);
    my_class->setDerived(new DerivedClass2);
    return 0;
}

Here is what valgrind says:

==10125== HEAP SUMMARY:
==10125==     in use at exit: 16 bytes in 2 blocks
==10125==   total heap usage: 3 allocs, 1 frees, 24 bytes allocated
==10125== 
==10125== Searching for pointers to 2 not-freed blocks
==10125== Checked 179,544 bytes
==10125== 
==10125== 8 bytes in 1 blocks are indirectly lost in loss record 1 of 2
==10125==    at 0x4C28C90: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10125==    by 0x40074E: main (AbstractFactory.cpp:32)
==10125== 
==10125== 16 (8 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==10125==    at 0x4C28C90: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10125==    by 0x400732: main (AbstractFactory.cpp:31)
==10125== 
==10125== LEAK SUMMARY:
==10125==    definitely lost: 8 bytes in 1 blocks
==10125==    indirectly lost: 8 bytes in 1 blocks
==10125==      possibly lost: 0 bytes in 0 blocks
==10125==    still reachable: 0 bytes in 0 blocks
==10125==         suppressed: 0 bytes in 0 blocks
==10125== 
==10125== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 3 from 3)
--10125-- 
--10125-- used_suppression:      3 dl-hack3-cond-1 /usr/lib/valgrind/default.supp:1196
==10125== 
==10125== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 3 from 3)

For me everything seems right. In line 31 memory is allocated and during setDerived method it is deallocated.

Thank You for any help.

Upvotes: 0

Views: 71

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129524

Your code is leaking, yes. And it's not a mystery either.

Really simple, you are never calling the destructor for my_class.

Add delete my_class; on the line just before return 0; in main.

Upvotes: 3

Related Questions