The standard way that I always use is to create a macro called MALLOC (or MYMALLOC or something else) that does what you want. All occurrences of MALLOC I have to replace with a macro, of course, and I can understand when this is not what you want.
You can also achieve what you want by specifying a macro named MALLOC (i.e. written as the original MALLOC ) only when compiling the source in which you want to use your function. This MALLOC macro MALLOC then call a function called, say, wrappingMalloc , which must be declared in a file that is compiled without defining the MALLOC macro and which, in turn, can call the original MALLOC function. If this make-script is too much for you, you can also call the original function by calling (malloc) (this avoids running the macro again):
#include <stdlib.h> #include <stdio.h> #define malloc(size) myMalloc(size) void *myMalloc(size_t size) { void *result; printf("mallocing %ld bytes", size); result = (malloc)(size); printf(" at %p\n", result); return result; } int main(int argc, char *argv[]) { char *buffer; buffer = malloc(10); return 0; }
In C ++, you can get by overloading the new operator for your classes.
source share