Wrapper functions for standard library functions


I would like to wrap some of the library functions such as malloc() into for example:

malloc_wrapper(int size) {
malloc(size+4); //call the real malloc here

and have all uses of malloc replaced with malloc_wrapper. Is there a way to do that?


I don’t know if there’s any way to do this directly in the compiler, but most linkers, including LLD, support a “–wrap” option. To wrap malloc(), you can use “–wrap=malloc” (or -Wl,–wrap=malloc if running through the compiler driver). This redirects all calls to malloc to a function called __wrap_malloc. If you want to subsequently call the real malloc function, you then call __real_malloc, so your example code above becomes:

__wrap_malloc(int size) {
__real_malloc(size+4); //call the real malloc here

Hope that helps.