奇怪的双重自由腐败(GCC 4.9.2,Clang3.6 on Ubuntu Vivid)

strange double free corruption (GCC 4.9.2, Clang3.6 on Ubuntu Vivid)

以下 MWE 给出了一个奇怪的地址清理报告:

#include <vector>

class A {
public:
    A(){}
    ~A(){}
};

class B{
public:

    B(){
        m_grid = new A();
    }
    ~B(){ delete m_grid;}

    A * m_grid = nullptr;

    std::size_t n;
};


int  main(){
    std::vector<B> l;
    l.emplace_back(B{});
}

AsanMangler 报告:

=================================================================
==14729==ERROR: AddressSanitizer: attempting double-free on 0x60200000eff0 in thread T0:
    #0 0x7f4207f6e6af in operator delete(void*) (/usr/lib/x86_64-linux-gnu/libasan.so.1+0x586af)
    #1 0x40126f in B::~B() /src/main.cpp:113
    #2 0x401efb in void std::_Destroy<B>(B*) /usr/include/c++/4.9/bits/stl_construct.h:93
    #3 0x401caa in void std::_Destroy_aux<false>::__destroy<B*>(B*, B*) /usr/include/c++/4.9/bits/stl_construct.h:103
    #4 0x4019c8 in void std::_Destroy<B*>(B*, B*) /usr/include/c++/4.9/bits/stl_construct.h:126
    #5 0x401546 in void std::_Destroy<B*, B>(B*, B*, std::allocator<B>&) /usr/include/c++/4.9/bits/stl_construct.h:151
    #6 0x40130f in std::vector<B, std::allocator<B> >::~vector() /usr/include/c++/4.9/bits/stl_vector.h:424
    #7 0x401057 in main /src/main.cpp:170
    #8 0x7f42075d9a3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20a3f)
    #9 0x400ea8 in _start (/src/MAIN+0x400ea8)

0x60200000eff0 is located 0 bytes inside of 1-byte region [0x60200000eff0,0x60200000eff1)
freed by thread T0 here:
    #0 0x7f4207f6e6af in operator delete(void*) (/usr/lib/x86_64-linux-gnu/libasan.so.1+0x586af)
    #1 0x40126f in B::~B() /src/main.cpp:113
    #2 0x401045 in main /src/main.cpp:124
    #3 0x7f42075d9a3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20a3f)

previously allocated by thread T0 here:
    #0 0x7f4207f6e1af in operator new(unsigned long) (/usr/lib/x86_64-linux-gnu/libasan.so.1+0x581af)
    #1 0x4011ea in B::B() /src/main.cpp:111
    #2 0x401020 in main /src/main.cpp:124
    #3 0x7f42075d9a3f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20a3f)

SUMMARY: AddressSanitizer: double-free ??:0 operator delete(void*)
==14729==ABORTING

编译:

/usr/bin/g++   -std=c++11 -ftree-vectorize -ftree-vectorizer-verbose=0 -fmessage-length=0 -Wno-enum-compare -g -fsanitize=address -o MAIN main.cpp

有人知道问题出在哪里吗?这里有一些非常可疑的东西,编译器错误或奇怪的标准库??,到目前为止,我还没有对 ubuntu vivid 中的 c++ 4.9 头文件做任何事情。或者它可能是地址消毒器的误报?

我安装了 clang-3.6 和

它也因以下行而崩溃:

clang++   -std=c++14 -fmessage-length=0 -Wno-enum-compare -g -o MAIN main.cpp

没什么奇怪的。指针没有 move,指针将被浅层复制,然后您将获得双重释放。您可以使用 std::unique_ptr 而不是原始指针,或者编写移动构造函数,这会将 nullptr 分配给指针。

B(B&& rhs) : m_grid(rhs.m_grid), n(rhs.n)
{
   rhs.m_grid = nullptr;
   rhs.n = 0;
}

那不是你使用 emplace_back 的方式。该函数的全部要点在于它避免了 movecopy 构造,而是进行就地构造,将参数转发给构造函数。事实上,push_back 委托给 emplace_back。所以你有一个不必要的 move/copy.

其次,为什么是三法则?为什么不是零规则?

class B{
public:
    std::vector<A> m_grid;
};

好了,现在您无需担心手动资源管理。