Bump allocator
This commit is contained in:
parent
29fbcca987
commit
d0aa85f62e
1 changed files with 59 additions and 0 deletions
59
bump.c
Normal file
59
bump.c
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
#include <assert.h>
|
||||
#include <limits.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define BUFSIZE (1024)
|
||||
static uint8_t some_large_buf[BUFSIZE] = {0};
|
||||
|
||||
typedef struct {
|
||||
uint8_t *buf;
|
||||
size_t buflen;
|
||||
size_t bufptr;
|
||||
} fast_alloc_t;
|
||||
|
||||
void *fast_alloc(fast_alloc_t *fa, size_t s) {
|
||||
if (fa->bufptr + s > fa->buflen) {
|
||||
return NULL;
|
||||
}
|
||||
void *p = fa->buf + fa->bufptr;
|
||||
fa->bufptr += s;
|
||||
return p;
|
||||
}
|
||||
|
||||
void fast_alloc_init(fast_alloc_t *fa, uint8_t *buf, size_t buflen) {
|
||||
fa->buf = buf;
|
||||
fa->buflen = buflen;
|
||||
fa->bufptr = 0;
|
||||
}
|
||||
|
||||
void fast_alloc_wipe(fast_alloc_t *fa) {
|
||||
fa->bufptr = 0;
|
||||
memset(fa->buf, 0, fa->buflen);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
fast_alloc_t fa = {0};
|
||||
fast_alloc_init(&fa, some_large_buf, BUFSIZE);
|
||||
|
||||
int *a = fast_alloc(&fa, sizeof(int));
|
||||
*a = 10;
|
||||
|
||||
int *b = fast_alloc(&fa, sizeof(int));
|
||||
*b = INT_MAX;
|
||||
|
||||
printf("Number: %d\n", *a);
|
||||
printf("Number: %d\n", *b);
|
||||
assert(*a == 10);
|
||||
assert(*b == INT_MAX);
|
||||
|
||||
fast_alloc_wipe(&fa);
|
||||
|
||||
printf("Number: %d\n", *a);
|
||||
printf("Number: %d\n", *b);
|
||||
assert(*a != 10);
|
||||
assert(*b != INT_MAX);
|
||||
|
||||
printf("All ok!\n");
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue