So I said I was going to start working on my game engine project, and I know it seems like I've been doing a whole lot of nothing, but I've been working this whole time! ...Well some of this whole time.
Working on what? On Memory!
I've written a few different memory algorithms now, but I'll start with the simplest: a Stack Allocator.
--> Open StackAllocator.cpp in a new window <--
The code above is hosten on Google Code, and you can comment by double clicking anywhere, or by clicking in the left hand margin on the little speech balloon plus icon. You need to be signed in with a google account. Please comment and tell me if my code sucks!
A stack allocator is useful in games because many games allocate memory for levels in a stack like manner. When a new game level is loaded, the memory for all the textures and meshes etc is loaded at once, and then nothing more is allocated during the duration of the level. When the level is unloaded, all of the memory is freed. A stack memory allocator is perfect for this sort of application.
Implementing a stack allocator is pretty simple:
- In the constructor, malloc a block of memory to use as the stack, and set it as the base of the stack and as the current top (ensuring it's not NULL).
- When memory is requested from the stack, store the address of the current top to return, and then move the current top up by the size requested.
- When freeing, you just set the current top back to the marker passed to the freeToMarker function.
- Clear the stack by setting the current top back to the base of the stack.
- When deleting the whole stack, you can ensure all memory has been freed by asserting that the current top is the same memory address as the base.
The next write up I believe will be Pool Allocators.