I am trying to hack the malloc function to call my malloc function first.Once my malloc function is executed within that, I want to invoke the standard malloc. But, I am getting
The standard way I'm always using is creating a macro called MALLOC
(or MYMALLOC
or whatever) which does what you want. All occurrences of malloc
I have to replace by the use of the macro, of course, and I can understand when this is not what you want.
You also can achieve what you want by defining a macro called malloc
(i. e. spelled like the original malloc
) only when compiling the source you want to have your feature in. This malloc
macro then would call a function called, say, wrappingMalloc
which should be declared in a file which is compiled without defining the macro malloc
and which then in turn can call the original function malloc
. If this makefile fiddling is too much for you, you could also call the original function by calling (malloc)
(this avoids running into the macro again):
#include
#include
#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 might get along by overloading the new
operator for your classes.