3 ms·
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 "b
by apgwoz 13y ago
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.
- apgwoz 13y agoUrr.. That should have been MAX, not MIN.
- munificent 13y ago> Freeing it is a bit of pain of course, but you could build a freelist out of the chunks that are 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