clinuxgcc

can I overwrite the malloc called by library functions?


my code (main.c):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void* __real_malloc(size_t size);
void __real_free(void* ptr);

void* __wrap_malloc(size_t size)
{
    void *ptr = __real_malloc(size);
    printf("custom malloc size=%ld ptr=%p\n", size, ptr);
    return ptr;
}

void __wrap_free(void* ptr)
{
    printf("custom free ptr=%p\n", ptr);
    __real_free(ptr);
}

// gcc -o mybin main.c -Wl,--wrap=malloc -Wl,--wrap=free
int main() {

    const char *original = "Hello, World!";
    char *copy;

    copy = strdup(original);
    printf("Original: %s\n", original);
    printf("Copy: %s\n", copy);

    void *ptr = malloc(100);

    free(ptr);
    free(copy);

    return 0;
}

my output:

Original: Hello, World!
Copy: Hello, World!
custom malloc size=100 ptr=0x55a845ef06d0
custom free ptr=0x55a845ef06d0
custom free ptr=0x55a845ef02a0

man page says strdup calls malloc. why don't I see two 'custom malloc' calls in the output? when I call malloc, it's the custom one. when strdup calls it, it's the standard one. why ?

env: simple x86 VM running Ubuntu


Solution

  • Linker can wrap only in functions that are being compiled. You are calling printf, which is defined in libc, which linker can't change.

    Ususally custom mallocs are loaded with LD_PRELOAD.