Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ - overriding default functions

I have the following question:

Does Microsoft Visual Studio (I'm using 2008 SP1) offer any way to override standart C functions such as malloc, memcpy?

Suppose I have some externally built library, which contains malloc.obj and memcpy.obj. Library is called library.lib.

How should I build my project so that the compiler uses my (overriden) versions of malloc() and memcpy() routines instead of those provided (I assume they share the same syntax)?

The point of whole this thing is about changing every malloc in my project without making name aliases like my_malloc or similiar, so that I could compare performance.

Is this possible?

Thank you.

like image 730
Yippie-Ki-Yay Avatar asked Dec 21 '22 22:12

Yippie-Ki-Yay


2 Answers

Is it possible to change the build and link process so that you replace the implementation of memcpy and malloc? Yes. Is it a good idea? Not really.

You'd be better off just using #define logic to rename those functions to something like memcpy_testing and malloc_testing, and then have a single #define that switches between the two. That way your solution is more portable to other build systems, and it's more immediately clear to other programmers what on earth you're doing.

Edit: In keeping with the comments, here is a sample of what you'd do in a shared header file:

#ifdef testing
#    define my_malloc(n) testing_malloc(n)
#else
#    define my_malloc(n) malloc(n)
#endif

You could even support run-time switching if need be by using function pointers:

void *(__cdecl *my_malloc)(size_t);
// ...
void SetToTest() { my_malloc = testing_malloc; }
void SetToStandard() { my_malloc = malloc; }
like image 178
Reinderien Avatar answered Jan 04 '23 22:01

Reinderien


Have not tried this but - in Project properties -> Linker -> Input, set 'Ignore All Default Libraries' to Yes. Then set 'Additional Dependencies' = library.lib;libcmt.lib.

This ought to include your library ahead of the standard static CRT. Provided function linkage is the same in each this should do what you want. Though how malloc/free are linked to the OS in the two static libs may be problematic. I assume library.lib also redefines realloc/free/calloc etc?

like image 40
Steve Townsend Avatar answered Jan 05 '23 00:01

Steve Townsend