问题
Is there a way to hook the malloc/free function call from a C application it self?
回答1:
Yes you can. Here's an example program. It compiles and builds with gcc 4.8.2 but does not run since the implementations are not functional.
#include <stdlib.h>
int main()
{
int* ip = malloc(sizeof(int));
double* dp = malloc(sizeof(double));
free(ip);
free(dp);
}
void* malloc(size_t s)
{
return NULL;
}
void free(void* p)
{
}
回答2:
malloc()
and free()
are defined in the standard library; when linking code, the linker will search the library only for symbols that are not already resolved by eailier encountered object code, and object files generated from compilation are always linked before any libraries.
So you can override any library function simply by defining it in your own code, ensuring that it has the correct signature (same name, same number and types of parameters and same return type).
回答3:
As many mentioned already, this is very platform specific. Most "portable" way is described in an accepted answer to this question. A port to non-posix platforms requires finding an appropriate replacement to dlsym
.
Since you mention Linux/gcc, hooks for malloc would probably serve you the best.
回答4:
Not sure if this counts as "overwriting', but you can effectively change the behavior of code that calls malloc
and free
by using a macro:
#define malloc(x) my_malloc(x)
#define free(x) my_free(x)
void * my_malloc(size_t nbytes)
{
/* Do your magic here! */
}
void my_free(void *p)
{
/* Do your magic here! */
}
int main(void)
{
int *p = malloc(sizeof(int) * 4); /* calls my_malloc */
free(p); /* calls my_free */
}
回答5:
C does not provide function overloading. So you cannot override.
回答6:
Depending on the platform you are using, you may be able to remove the default malloc/free from the library and add your own using the linker or librarian tools. I'd suggest you only do this in a private area and make sure you can't corrupt the original library.
回答7:
On the Windows platform there is a Detour library. It basically patches any given function on the assembler level. This allows interception of any C library or OS call, like CreateThread
, HeapAlloc
, etc. I used this library for overriding memory allocation functions in a working application.
This library is Windows specific. On other platforms most likely there are similar libraries.
来源:https://stackoverflow.com/questions/24893413/is-there-a-way-to-overwrite-the-malloc-free-function-in-c