LD_PRELOADing malloc e grátis
Eu escrevi meu própriomalloc elivre e compilou-os em uma biblioteca compartilhada. LD_PRELOAD essa biblioteca com o meu programa. Dessa forma, meu programa sempre usaria meumalloc elivre ou há casos em que não é assim. Ouvi dizer que o gcc foi construído em malloc elivre também. É possível que o glibc que veio com o meu gcc está usando o builtinmalloc elivre.
Em segundo lugar, noto que quando executo meu programa, estou vendolivre chamada de função mais frequentemente do que omalloc / calloc chamadas (98 a 16). Eu não faço nenhuma alocação de memória (exceto em um lugar), então toda a alocação está sendo feita pelas funções padrão da biblioteca que eu uso. E também note que estou usando o pthread no meu programa. Se você quiser saber, meu programa se parece com isso.
#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;
}