I don't need any of this, it's for fun
I implemented realloc on linux before using map and mremap. I ran dtruss on the below code and I see two write calls, nothing in between. Using bash and time b.c is significantly slower than a.c which leaves me to believe realloc doesn't use a memcpy (and likely changes virtual pages).
If I wanted to implement my own C library or write a realloc in assembly how would I implement it to get as good performance as a.c?
% cat a.c b.c
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main() {
write(1, "Hel", 3);
void*p1=malloc(1024*1024*512);
memset(p1, '1', 1024*1024*512);
malloc(4096);
void*p =realloc(p1, 1024*1024*1024);
memset(p+1024*1024*512, '0', 1024*1024*512);
write(1, "lo\n", 3);
}
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main() {
write(1, "Hel", 3);
void*p1=malloc(1024*1024*512);
memset(p1, '1', 1024*1024*512);
void*p =malloc(1024*1024*1024);
memcpy(p, p1, 1024*1024*512);
memset(p+1024*1024*512, '0', 1024*1024*512);
write(1, "lo\n", 3);
}