segfault with dlsym(RTLD_NEXT, "func")

nirnimesh_at_gmail.com
Date: 10/22/05


Date: 22 Oct 2005 08:43:45 -0700

I'm trying to intercept malloc() for accounting. In turn, I'm calling
the real malloc to return back the mem-pointer. This is as described at
http://ou800doc.caldera.com/en/man/html.3C/dlsym.3C.html
That is, intercept_malloc.c looks like:

void * malloc(size_t sz)
{
    printf("start\n");
    void *ptr;
    void *(*real_malloc)(size_t);

    real_malloc = (void * (*)(size_t))dlsym(RTLD_NEXT, "malloc");
    ptr = (*real_malloc)(sz);
    printf("end");
    return ptr;
}

This is compiled as:
    gcc -shared -o record_malloc.so -fPIC record_malloc.c

My main.c is:

int main()
{
    void* mem = malloc(20);
    return 0;
}

I run this main program as:
    LD_PRELOAD=./record_malloc.so ./main
This results in a segfault after printing "start". Basically, the dlsym
function returns NULL, I think.

What am I doing wrong?

I'm using FC4 with gcc 4.0.0