Interesting. Golang _runtime_ requires malloc, so even if used carefully I doubt you could use go in this way.
So, the suggestion looks like this:
struct freemem {
int len;
char *addr;
struct freemem *next;
};
// globals
int total_mem_size;
char *start_of_memory;
char *bump_pointer;
struct freemem *freelist;
Allocate is simply: if bump_pointer + MIN(size_to_allocate, sizeof(struct freemem)) < total_mem_size:
int *b = (int *) bump_pointer;
*b = MIN(size_to_allocate, sizeof(struct freemem);
return b + sizeof(int)
else
iterate over freelist, checking for size_to_allocate < freelist->len
return freelist->addr (the *b business is already taken care of)
Deallocate simply turns the discarded memory into a struct freemem and prepends it to the freelist, setting addr = the discarded address, and len = *(addr - sizeof(int)) (it's for this reason that we allocate a minimum size of sizeof(struct freemem))That's a basic malloc / free.
If you want a much longer explanation of this technique, I wrote a chapter about object pools[1] that discusses exactly this[2].
[1] http://gameprogrammingpatterns.com/object-pool.html
[2] http://gameprogrammingpatterns.com/object-pool.html#faster-particle-creation