• Uncategorized

About c : LDPRELOADing-malloc-and-free

Question Detail

I wrote my own malloc and free and compiled them in a shared library. I LD_PRELOAD that library with my program. In this way would my program always use my custom malloc and free or are there cases where it is not so. I’ve heard that gcc has built in malloc and free too. Is it possible that the glibc that came with my gcc is using the builtin malloc and free.

Secondly, I notice that when I run my program, I’m seeing the free function call more often than the malloc/calloc calls (98 to 16). I don’t do any memory allocation myself (except in one place), so all allocation is being done by standard library functions that I use. And also note I’m using pthread in my program. If you want to know, my program looks like this.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>

#define NUM_THREADS     8

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

int sum;
float total = 1;
extern int __did_libc_start_main;

void *PrintHello(void *threadid)
   long tid;
   tid = (long)threadid;
   pthread_mutex_lock( &m );
   total *= total + tid * 0.097891313423578;
   printf( "p%d, tid%d, total = %g, start = %d!\n", getpid(), tid, total, 0 );
   pthread_mutex_unlock( &m );
   printf("Hello World! It's me, thread #%ld!\n", tid);

int main (int argc, char *argv[])
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   char * p;
   char * m;


   p = (char*)mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
   p[0] = 78;
   printf( "p = %p, p[0] = %d, pid = %d!\n", p, p[0], getpid() );
   m = (char*)malloc( 80 );
   printf( "m = %p!\n", m );
#if 1  
   for(t=0; t<NUM_THREADS; t++)
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
   for(t=0; t<NUM_THREADS; t++)
    pthread_join(threads[t], NULL);

   printf( "\n\nTotal = %g\n\n", total );

   /* Last thing that main() should do */
   printf( "\n\n%d: Done without major problems\n\n", getpid() );
   return 0;

Question Answer

Using LD_PRELOAD to override malloc etc. is expected to work; this is how e.g. DUMA works.

In addition to malloc, calloc and free, make sure you override realloc, memalign and valloc. In addition you might need to override C++ new, new[], delete and delete[].

See Overriding ‘malloc’ using the LD_PRELOAD mechanism for an example of how to do this right.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.