MoarVM/MoarVM — pull request #125 by cono (2014-08-19 15:01:31+00:00)
Title: c static allocator

Hello guys,

I would like to present you my idea of spliiting 2 types of allocations:
1. dynamic (with possible further reallocs)
2. static - for code kinda like this: cstalloc(sizeof(SOME_STRUCT)) limited by size 1kb (can be increased via #defines).

Would you mind to review the following C static allocator?

I made some dumb tests:
```
#include

#ifdef CST

#include "cstalloc.h"

#define mvmalloc(size)	cstalloc(size)
#define mvmfree(ptr)	cstfree(ptr)

#else

#include

#define mvmalloc(size)	malloc(size)
#define mvmfree(ptr)	free(ptr)

#endif

#define CNT 256

typedef struct {
int x;
int y;
} test_t;

test_t *data[CNT];

int
main(int argc, char **argv) {
int i, c = 1000000;

printf("sizeof: %ld\n", sizeof(test_t));

while (--c) {
for (i = 0; i < CNT; ++i) {
data[i] = mvmalloc(sizeof(test_t));

data[i]->x = c;
data[i]->y = c + 1;
}

for (i = CNT - 1; i >= 0; --i) {
if (data[i]->x != c || data[i]->y != (c + 1)) {
printf("wrong: x=%d, y=%d\n", data[i]->x, data[i]->y);
}
mvmfree(data[i]);
}
}

printf("done\n");
}
```

runs:
```
% gcc -DCST -o test_cst ./test.c cstalloc.o
% gcc -o test_malloc ./test.c cstalloc.o

% time ./test_cst
sizeof: 8
done
./test_cst 4.97s user 0.01s system 100% cpu 4.971 total

% time ./test_malloc
sizeof: 8
done
./test_malloc 7.69s user 0.01s system 100% cpu 7.693 total
```

Also, I made a stub for cstgc - function which will give memory back to the system if possible. I already have algorithm in mind but need some time to code and debug it.

I'm open for any critic. And proposing this change just for discussion if this is a viable solution or just some piece of garbage :)