首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LD_PRELOADing malloc和free

LD_PRELOADing malloc和free
EN

Stack Overflow用户
提问于 2012-06-06 11:20:29
回答 1查看 1.6K关注 0票数 1

我编写了自己的malloc,并免费地将它们编译在一个共享库中。我用我的程序LD_PRELOAD那个库。这样,我的程序将始终使用我的自定义malloc和免费的,或者在一些情况下它不是这样的。我听说gcc建在马洛克,也是自由的。有没有可能跟我的gcc一起来的滑雪板用的是内置的马洛和免费的。

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

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-06 12:19:59

使用LD_PRELOAD来覆盖malloc等是应该的;例如,杜马就是这样工作的。

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

有关如何正确执行此操作的示例,请参阅预紧机构

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10913186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档