aboutsummaryrefslogtreecommitdiff
path: root/src/utils.c
blob: 1baf28311776888482ec2dc8ac6d4a87d37daed2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "utils.h"

#include <stdio.h>
#include <assert.h>

struct allocator {
    void** bufs;
    size_t cap;
    size_t len;
};

Allocator newAllocator() {
    Allocator alct = malloc(sizeof(struct allocator));
    alct->bufs = malloc(sizeof(void*) * 16);
    alct->cap = 16;
    alct->len = 0;
    alct->bufs[0] = NULL;
    return alct;
}

void deleteAllocator(Allocator alct) {
    for (size_t i = 0; i < alct->len; i++) {
        free(alct->bufs[i]);
    }
    free(alct->bufs);
    free(alct);
}

void * allocate(Allocator alct, size_t size) {
    assert(size > 0);
    if (alct->len >= alct->cap) {
        alct->cap = alct->cap * 2; // Doubling the capacity
        alct->bufs = realloc(alct->bufs, sizeof(void*) * alct->cap);
    }

    void* ptr = malloc(size); // Allocate requested size
    alct->bufs[alct->len] = ptr; // Store pointer in array
    alct->len++;
    return ptr;
}