Crap that I say
News that isn't boring
How I waste my time

My pretend social life
Waste your money on me
My Amazon.com Wish List
« Pool Allocator | Main | LED Pac-man in Assembly »
Wednesday
Jul132011

Stack Allocator

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:

  1. 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).
  2. 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.
  3. When freeing, you just set the current top back to the marker passed to the freeToMarker function.
  4. Clear the stack by setting the current top back to the base of the stack.
  5. 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.

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>