I recently have been very interested in custom allocators, so I decided to make the very basic (this should be faster than malloc
) bump allocator. Here is my code in C:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/mman.h>
#include <unistd.h>
#define KB(size) ((size_t) size * 1024)
#define MB(size) (KB(size) * 1024)
#define GB(size) (MB(size) * 1024)
#define HEAP_SIZE GB(1)
typedef intptr_t word_t;
void* free_ptr = NULL;
void* start_ptr;
word_t end_ptr;
void init() {
free_ptr = mmap(NULL, HEAP_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (free_ptr == MAP_FAILED) {
printf("unable to map memory\n");
abort();
}
start_ptr = free_ptr;
end_ptr = (word_t) start_ptr + HEAP_SIZE;
}
void* bump_alloc(size_t size) {
void* new_ptr = free_ptr;
free_ptr = (char*) free_ptr + size;
return new_ptr;
}
void free_all_mem() {
munmap(start_ptr, HEAP_SIZE);
}
int main() {
init();
int* x = (int*) bump_alloc(sizeof(int));
assert(x != NULL);
*x = 10000;
printf("x: %d\n", *x);
free_all_mem();
}
This is my first custom allocator so could I get some tips on optimization, etc.
GB(10*1024)
etc will overflow. Don't use function-like macros for these, use absolute numeric constants. \$\endgroup\$malloc
returns (applies to your malloc as well). \$\endgroup\$GB(10*1024)
overflows 32-bit math? Overwise(size_t)10* 1024 * 1024 *1024
looks OK. \$\endgroup\$