But, malloc doesn't have to be significantly advanced. In a situation where you have a large chunk of memory unallocated, the simplest thing to do is just to "bump" allocate it. Freeing it is a bit of pain of course, but you could build a freelist out of the chunks that are free.
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.