I’ve been experimenting with Electric Fence lately and I can’t figure out how to use it with c++ code.
Here’s an example:
// test.cpp #include <cstdlib> using namespace std; int main() { int *a = new int(10); delete a; }
I compiled it with
g++ ./test.cpp -o test -lefence -L/home/bor/efence_x86_64/lib -lpthread
And I don’t see Electric Fence banner at the start and can’t find EF symbols in the executable (using nm command).
But if I modify a program like so:
// test.cpp #include <cstdlib> using namespace std; int main() { char *p = (char*)malloc(20); free(p); int *a = new int(10); delete a; }
everything is good – EF appears. I know it kinda solves the problem, I know :). I just want to understand why it didn’t work in the first place, because new()
should call malloc()
, and delete()
calls free()
, no?
The reason I got into this is a big project using boost libraries and several others. And this program never calls malloc()
or free()
directly. And when I build it with EF not I only linked EF to the final executable but rebuilt all the libraries trying to link EF to them. And I can’t find EF symbols in either one of them. Is it the right approach? Or is it wrong and EF only should be linked to the executable in the end, the libs should be left intact? But again I can’t find EF symbols in the executable then.
Advertisement
Answer
You are assuming that the compiler is compiling the code behind new
, but that code generally resides somewhere in a pre-compiled RT.
new
also doesn’t generally call malloc
directly (on some systems like Windows, it doesn’t call malloc
at all), it has a few tasks of its own that are performed, before and after it handles the allocation. for something like this you might have to go the semi-evil route of globally overloading new
and delete
to force it to directly call malloc
and free
from your code.