Thursday, November 13, 2008

Doug Lea's Malloc

Alguna vez te preguntaste ¿cómo es que funciona la llamada a malloc?. Dejame decirte que te haces muy buenas preguntas y las respuestas son MUY interesantes. =D

http://g.oswego.edu/dl/html/malloc.html
ftp://g.oswego.edu/pub/misc/malloc.c


#include <stdio.h>
#include
<stdlib.h>
#include
<string.h>

int main (int argc, char *argv[]){
char *p;
int size,malloc_size;

if(argc != 2){
printf(
"Uso: %s size\n",argv[0]);
exit(
-1);
}

size
= atoi(argv[1]);
printf(
"--------[ Probando para size: %d bytes\n",size);
p
=(char *)malloc(size);
memcpy(
&malloc_size,p-4,4);
malloc_size
&=~7; //Quitamos las banderas
printf("--------[ Malloc size: %d\n",malloc_size);
free(p);
return 0;
}


Obviamente, que al código le hace falta quitarle los bytes que utilizan los boundary tags.