Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally override malloc in visual c++

I'm trying to figure out a way to globally override malloc and related functions in visual c++ (2005). My setup is a dll with statically linked runtime library that consists of both my own c++ code, external c++ and c code. What I want to accomplish is to allow a user of the dll to set their own implementations of the memory allocation functions.

Solutions that I can't use:

  • Overriding new and delete globally, there is lots of external C libraries in my code base which means this won't capture many allocations.
  • # defining malloc to a different symbol. This would force me to push this define into the build settings of all external libraries used and I really want to avoid this.

Things I don't care about:

  • If any of the external libraries are allocating memory in some other way (HeapAlloc, memory mapped files or whatever they come up with), I accept that this won't be tracked properly by overriding malloc.

The most reasonable solution I can come up with is somehow interfering with the link process and making sure my own malloc is being linked instead of the standard ones, preferably I'd like to be able to use the old malloc functions as default.

In google perf-tools it seems like they patch the code of the functions manually at runtime to allow a hook function to be called before calling the original function. Is this really the best way of doing this?

like image 630
Laserallan Avatar asked Aug 22 '09 13:08

Laserallan


1 Answers

I'm keen to find a neat solution for this too. We compile for multiple platforms, so on the non-windows side of things we can use --wrap happily. We just have to create the replacement functions and it all works without any errors or hacks.

On the windows side of things, we override the malloc calls, but then use /FORCE:MULTIPLE to deal with the linker errors. It works, the memory functions are called and everything is tracked, but it feels like a hack.

From MSDN:

A file created with this option may not run as expected. The linker will not link incrementally when the /FORCE option is specified.

Not only does it feel like a hack, it kills edit and continue in the process.

The /FORCE:MULTIPLE option might fix your problems, but I'm not suggesting it as a cure, I'm still trying to find that.

MSDN /FORCE Documentation

: D

like image 145
Danny Parker Avatar answered Oct 09 '22 02:10

Danny Parker