Skip to content

Instantly share code, notes, and snippets.

@srishanbhattarai
Last active October 3, 2020 08:40
Show Gist options
  • Save srishanbhattarai/e2d19fdc780dbd38e7038541d0ca2c7a to your computer and use it in GitHub Desktop.
Save srishanbhattarai/e2d19fdc780dbd38e7038541d0ca2c7a to your computer and use it in GitHub Desktop.
An example of a small custom memory allocator that contiguously allocates space for a linkedlist to prevent excessive jumps. Please don't use this code. There's several ways this can be improved.
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
// 16 byte struct
typedef struct Node {
int64_t value;
struct Node* next;
} Node;
// A linked list allocator of 'count' objects.
typedef struct Alloc {
void* head;
uint64_t count;
} Alloc;
// Initializes the allocator for count nodes
void init_alloc(Alloc* alloc, uint64_t count) {
void* head = malloc(sizeof(Node) * count);
alloc->head = head;
alloc->count = 0;
}
void insert_value(Alloc* alloc, uint64_t value) {
Node* pointer_to_insert_at = (Node*) alloc->head + alloc->count;
pointer_to_insert_at->value = value;
alloc->count++;
}
void print_values(Alloc* alloc) {
for (int i = 0; i < alloc->count; ++i) {
Node* n = (Node*) alloc->head + i;
printf("Node #%d: %lld\n", i, n->value);
}
}
// cleanup
void destroy_alloc(Alloc* alloc) {
free(alloc->head);
}
int main() {
const uint64_t num_nodes_to_alloc = 1000;
Alloc alloc;
init_alloc(&alloc, num_nodes_to_alloc);
for (int i = 0; i < num_nodes_to_alloc; i++) insert_value(&alloc, i);
print_values(&alloc);
destroy_alloc(&alloc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment