我正在编写一个可以在多个系统上运行的库(其中一些没有标准库malloc
或标准库)。在我的标准库(不同的库)中,我重写了new
anddelete
运算符来对函数进行通用调用(这个例子没有这些函数)。每个系统都会覆盖这些对它们各自内存分配设备的通用调用。
问题是当我尝试这样做时。这是一些简化的示例代码来重现该问题:
#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。