Skip to main content
Tweeted twitter.com/StackCodeReview/status/1267742762595758080
Became Hot Network Question
edited title
Link
xilpex
  • 289
  • 3
  • 14

C - Fast custom& simple bump allocator

Source Link
xilpex
  • 289
  • 3
  • 14

C - Fast custom bump allocator

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.