valgrind不抱怨内存损坏?

时间:2014-11-26 12:17:29

标签: c++ valgrind memory-corruption

我有一小段代码作为打击

class singler
{
    private:
        singler() { _id = id++; };
    public:
        ~singler() { cout<<"In destructor of "<<_id<<endl;};
        static singler* allocate() { singler* p = new singler(); return p; };
        static int id;
        int _id;
};
int singler::id = 0;
singler& create_new(singler*& ptr)
{
    singler * p = singler::allocate();
    ptr = p;
    return (*p);
}
int main()
{
    singler* ptr;
    singler obj = create_new(ptr);
    delete ptr;
}

所以你可以看到对象的析构函数将被调用两次,作为证明,我编译并运行它,它输出为

In destructor of 0
In destructor of 0

问题在于valgrind,它不会抱怨什么,valgrind输出如下 == 2

0408== Memcheck, a memory error detector
==20408== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20408== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20408== Command: a.out
==20408==
In destructor of 0
In destructor of 0
==20408==
==20408== HEAP SUMMARY:
==20408==     in use at exit: 0 bytes in 0 blocks
==20408==   total heap usage: 1 allocs, 1 frees, 4 bytes allocated
==20408==
==20408== All heap blocks were freed -- no leaks are possible
==20408==
==20408== For counts of detected and suppressed errors, rerun with: -v
==20408== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)

那么如何有效地检测这类错误呢? (我的意思是使用一些工具,至少会告诉我是否有任何问题,如果是的话,它在哪里?)

1 个答案:

答案 0 :(得分:6)

你的程序没有腐败,valgrind在你的情况下工作正常。

确实创建了两个对象。第一个对象在堆上分配,第二个对象是第一个对象的副本。这就是你看到析构函数被调用两次的原因。