Skip to content

Instantly share code, notes, and snippets.

@spratt
Created February 1, 2016 13:39
Show Gist options
  • Save spratt/676b6a43ec32a80bb38d to your computer and use it in GitHub Desktop.
Save spratt/676b6a43ec32a80bb38d to your computer and use it in GitHub Desktop.
A bad implementation of malloc using only mmap.
#include <sys/mman.h>
#include <stdio.h>
void* mymalloc(size_t len) {
void* addr = mmap(0,
len + sizeof(size_t),
PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE,
-1,
0);
*(size_t*)addr = len;
return addr + sizeof(size_t);
}
int myfree(void* addr) {
return munmap(addr - sizeof(size_t), (size_t) addr);
}
int main(int argc, char* argv[]) {
puts("Allocating space...\n");
int* heap_integer = mymalloc(sizeof(int));
puts("Writing to allocated space...\n");
*heap_integer = 5;
puts("Reading from allocated space...");
printf("Heap-allocated integer: %d\n", *heap_integer);
myfree(heap_integer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment