For details on building a shared library, look here.
If my library contains this
#include "lib.h"
class InvalidFree
{
public:
InvalidFree() : mem(new int[1]) {}
~InvalidFree() { delete mem; }
private:
int *mem;
};
InvalidFree invalidFree;
int foo()
{
return 42;
}
Note in the above I've mixed up using new []
and delete
. I should have used delete []
.
And I compile the lib with g++ -o liblib.so -shared -O3 lib.cpp -fPIC
then Valgrind gives me
==25378== Mismatched free() / delete / delete []
==25378== at 0x402E0FB: operator delete(void*, unsigned long) (vg_replace_malloc.c:593)
==25378== by 0x5B7DED9: __cxa_finalize (in /usr/lib64/libc-2.17.so)
==25378== by 0x403C132: ??? (in /example/path/liblib.so)
==25378== by 0x400FFC9: _dl_fini (in /usr/lib64/ld-2.17.so)
==25378== by 0x5B7DB68: __run_exit_handlers (in /usr/lib64/libc-2.17.so)
==25378== by 0x5B7DBB6: exit (in /usr/lib64/libc-2.17.so)
==25378== by 0x5B663DB: (below main) (in /usr/lib64/libc-2.17.so)
==25378== Address 0x5f22c80 is 0 bytes inside a block of size 4 alloc'd
==25378== at 0x402D57F: operator new[](unsigned long) (vg_replace_malloc.c:431)
==25378== by 0x403C07D: _GLOBAL__sub_I_lib.cpp (in /example/path/liblib.so)
==25378== by 0x400F902: _dl_init (in /usr/lib64/ld-2.17.so)
==25378== by 0x4001159: ??? (in /usr/lib64/ld-2.17.so)
If I change the -O3
to a -g
in the compiler options for the library then I get
==14347== Mismatched free() / delete / delete []
==14347== at 0x402DF1B: operator delete(void*) (vg_replace_malloc.c:584)
==14347== by 0x522495E: InvalidFree::~InvalidFree() (lib.cpp:7)
==14347== by 0x5C7EED9: __cxa_finalize (in /usr/lib64/libc-2.17.so)
==14347== by 0x5224862: ??? (in /example/path/liblib.so)
==14347== by 0x400FFC9: _dl_fini (in /usr/lib64/ld-2.17.so)
==14347== by 0x5C7EB68: __run_exit_handlers (in /usr/lib64/libc-2.17.so)
==14347== by 0x5C7EBB6: exit (in /usr/lib64/libc-2.17.so)
==14347== by 0x5C673DB: (below main) (in /usr/lib64/libc-2.17.so)
==14347== Address 0x6012040 is 0 bytes inside a block of size 4 alloc'd
==14347== at 0x402D57F: operator new[](unsigned long) (vg_replace_malloc.c:431)
==14347== by 0x5224939: InvalidFree::InvalidFree() (lib.cpp:6)
==14347== by 0x52248EB: __static_initialization_and_destruction_0(int, int) (lib.cpp:12)
==14347== by 0x5224920: _GLOBAL__sub_I_lib.cpp (lib.cpp:17)
==14347== by 0x400F902: _dl_init (in /usr/lib64/ld-2.17.so)
==14347== by 0x4001159: ??? (in /usr/lib64/ld-2.17.so)