我正在编写一个将在多个系统上运行的库(其中一些系统没有malloc
或stdlib)。在我的stdlib(不同的lib)中,我重写了new
和delete
操作符以对函数进行泛型调用(本示例没有这些函数)。每个系统将覆盖这些泛型调用到各自的内存分配设备。
问题是当我试图这样做。下面是一些简化的示例代码来重现这个问题:
#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
(没有参数)构建它并使用valgrind
(没有参数)运行时,我得到这个错误:
==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
多亏了Paul Floyd,这个bug已经在提交6ef6f738a中修复了。查看bug报告
然而,此修复尚未发布(截至2018年6月),并且可能需要更长的时间才能在发行版中显示。如果您现在需要此修复,我建议从源代码构建。