c++ - 神秘的内存泄漏

标签 c++ memory-leaks

我在互联网上有一些代码写得不完美,但在我看来没有内存泄漏。但是可以肯定的是,我使用了有不同意见的 valgrind。

代码如下:

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;
}

这是 valgrind 所说的:

==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)

对我来说一切似乎都是正确的。在第 31 行分配内存,并在 setDerived 方法期间释放内存。

感谢您的帮助。

最佳答案

是的,您的代码泄漏了。这也不是什么谜。

非常简单,您永远不会为 my_class 调用析构函数。

mainreturn 0; 之前的行中添加 delete my_class;

关于c++ - 神秘的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25461144/

相关文章:

iphone - MPMoviePlayerController 释放问题

c++ - 无法用 64 位 g++ 编译 32 位

读取文件后提取子 vector 时出现 C++ 错误

c++ - 检索和编辑 vector 中对象的私有(private)成员

c++ - 从另一个进程中获取内存

iPhone : little problem of memory leak with NSTimer

c++ - C++中的内存泄漏

c++ - 类派生设计

java - 泄漏了最初在此处添加的窗口 com.android.internal.policy.impl.PhoneWindow$DecorView{b5596468 V.E..... R.....ID 0,0-456,144}

c# - C++/CLI 代码中的内存泄漏。我做错了什么?