我正在编写一个可在多个系统上运行的库(其中一些系统没有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
(没有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。