Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to overwrite the malloc/free function in C?

Tags:

c

malloc

free

Is there a way to hook the malloc/free function call from a C application it self?

like image 950
Sujith Gunawardhane Avatar asked Jul 22 '14 17:07

Sujith Gunawardhane


People also ask

Can you overwrite malloc?

Overriding the standard malloc can be done either dynamically or statically.

Can you malloc after freeing?

Occasionally, free can actually return memory to the operating system and make the process smaller. Usually, all it can do is allow a later call to malloc to reuse the space. In the meantime, the space remains in your program as part of a free-list used internally by malloc .


3 Answers

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).

like image 167
Clifford Avatar answered Oct 28 '22 09:10

Clifford


Yes you can. Here's an example program. It compiles and builds with gcc 4.8.2 but does not do anything useful 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)
{
}
like image 43
R Sahu Avatar answered Oct 28 '22 09:10

R Sahu


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   */
}
like image 42
ApproachingDarknessFish Avatar answered Oct 28 '22 10:10

ApproachingDarknessFish