Valgrind报告不匹配f​​ree()/ delete / delete []

时间:2016-11-09 15:00:43

标签: c++ gcc valgrind new-operator gcc6

我正在编写一个可在多个系统上运行的库(其中一些系统没有malloc或stdlib)。在我的stdlib(不同的lib)中,我重写了newdelete运算符来对函数进行泛型调用(这个例子没有这些函数)。每个系统都会覆盖对各自内存分配设备的这些通用调用。

问题是当我尝试这样做时。以下是一些用于重现问题的精简示例代码:

#include <cstdlib>

void* operator new(unsigned long size) {
        return std::malloc(size); // would normally call an intermediate function which would be overridden by the system
}

void operator delete(void* object) {
        std::free(object); // would normally call an intermediate function which would be overridden by the system
}
void operator delete(void* object, unsigned long size) {
        std::free(object); // would normally call an intermediate function which would be overridden by the system
}

class MyClass {

};

int main() {
    MyClass* myClass = new MyClass();
    delete myClass;
}

当我使用普通gcc-6(没有args)构建它并使用valgrind(没有args)运行时,我收到此错误:

==11219== Mismatched free() / delete / delete []
==11219==    at 0x4C2DD6B: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==11219==    by 0x108730: operator delete(void*, unsigned long) (in /home/chris13524/tmp/test.o)
==11219==    by 0x10875A: main (in /home/chris13524/tmp/test.o)
==11219==  Address 0x5200040 is 0 bytes inside a block of size 1 alloc'd
==11219==    at 0x4C2D1AF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==11219==    by 0x108745: main (in /home/chris13524/tmp/test.o)

delete运算符似乎正常运行,但Valgrind正在覆盖我重写的new运算符。知道如何解决这个问题吗?

删除中间函数不是一个选项,因为我有其他代码。

它在我的真实程序中如何工作的示例(再次,在我的示例中未显示):

new => create => <intermediate code> => createImpl => malloc
create => <intermediate code> => createImpl => malloc

我使用gcc v6.2.0,valgrind v3.12.0和Ubuntu 16.10。

1 个答案:

答案 0 :(得分:0)

感谢Paul Floyd,这个错误已在提交6ef6f738a中修复。请参阅错误报告here

但是,此修复程序尚未发布(截至2018年6月),并且可能需要更长时间才能显示在发行版中。如果您现在需要此修复程序,我建议您从source构建。