There's no need to go through these steps if you're compiling the code yourself. If you want to override a library function like malloc, just define a function called malloc. Then make sure that the linker sees your function before the library function. For example, here I override pthread_create: https://github.com/scotts/streamflow/blob/master/override.c#...
Note that I also figure out, at runtime, how to call the real version of pthread_create using the dlsym interface. I make sure that my pthread_create is the first one in the call chain by putting that object file before -lpthread when I link.
The LD_PRELOAD method is for when you are not compiling the code yourself. That is, the function you want to hijack is in a binary, and you can't re-compile that binary. Then you compile a shared library with your function, and use LD_PRELOAD to force the runtime linker to load your library first.
Monkey patching is pretty common for when you want to override or get on-change notifications for interfaces that don't support it.
For example, have header files for functions? Want to know when they're called? Monkey patch it in!
Also, from what I've heard monkey patching a function is calling adding a detour, and monkey patching a virtual function is called hooking. "Monkey patching" usually refers to injecting code into dynamic languages, not into compiled languages.
Indeed, detours/hooking is the correct terminology here. I've never heard anyone ever refer to this as monkey patching when it's done on with a compiled language.
Note that I also figure out, at runtime, how to call the real version of pthread_create using the dlsym interface. I make sure that my pthread_create is the first one in the call chain by putting that object file before -lpthread when I link.
The LD_PRELOAD method is for when you are not compiling the code yourself. That is, the function you want to hijack is in a binary, and you can't re-compile that binary. Then you compile a shared library with your function, and use LD_PRELOAD to force the runtime linker to load your library first.