【问题标题】:LD_PRELOADing malloc and freeLD_PRELOADing malloc 和 free
【发布时间】:2012-06-10 09:47:36
【问题描述】:

我编写了自己的 mallocfree 并将它们编译到共享库中。我用我的程序 LD_PRELOAD 那个库。这样,我的程序将始终使用我的自定义 mallocfree 还是在某些情况下并非如此。我听说 gcc 也内置了 malloc 和 free。我的 gcc 附带的 glibc 是否有可能使用内置的 mallocfree

其次,我注意到当我运行我的程序时,我看到 free 函数调用比 malloc/calloc 调用更频繁(98 到 16)。我自己不进行任何内存分配(在一个地方除外),所以所有分配都是由我使用的标准库函数完成的。还要注意我在我的程序中使用 pthread 。如果你想知道,我的程序是这样的。

#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 );
   sum++;
   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);
   pthread_exit(NULL);
}

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

   fork();

   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);
         exit(-1);
      }
   }
   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 */
   pthread_exit(NULL);
#endif
   printf( "\n\n%d: Done without major problems\n\n", getpid() );
   return 0;
}

【问题讨论】:

标签: c linux gcc ld-preload


【解决方案1】:

使用LD_PRELOAD 覆盖malloc 等预计会起作用;这就是例如DUMA 有效。

除了malloccallocfree,请确保覆盖reallocmemalignvalloc。此外,您可能需要覆盖 C++ newnew[]deletedelete[]

有关如何正确执行此操作的示例,请参阅 Overriding 'malloc' using the LD_PRELOAD mechanism

【讨论】:

  • finnw: strdup 致电malloc
猜你喜欢
  • 1970-01-01
  • 2012-08-29
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
相关资源
最近更新 更多