Created
February 1, 2016 13:39
-
-
Save spratt/676b6a43ec32a80bb38d to your computer and use it in GitHub Desktop.
A bad implementation of malloc using only mmap.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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