I'm writing a library that will operate on multiple systems (some of which do not have malloc
or a stdlib). In my stdlib (different lib), I am overriding the new
and delete
operators to make generic calls to functions (this example doesn't have these functions). Each system will override these generic calls to their respective memory allocation devices.
The issue is when I attempt to do this. Here is some stripped down example code to reproduce the issue:
#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;
}
When I build it with plain gcc-6
(no args) and run with valgrind
(no args), I get this error:
==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)
It appears the delete
operator is working correctly, but Valgrind is overriding my overridden new
operator. Any idea how to fix this?
Removing the intermediate functions is not an option as I have other code in there.
Example of how it works on my real program (again, not shown in my example):
new => create => <intermediate code> => createImpl => malloc
create => <intermediate code> => createImpl => malloc
I'm using gcc v6.2.0, valgrind v3.12.0, and Ubuntu 16.10.
Thanks to Paul Floyd, this bug has been fixed in commit 6ef6f738a. See bug report here.
However, this fix hasn't been released yet (as of June 2018), and will likely take longer to show up in distributions. If you need this fix now, I suggest building from source.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With