Custom Allocator(1):Stack-Based Allocator

We simply allocate a large contiguous block of memory using malloc() or global new, or by delaring a global array of bytes. A pointer to the top of the stack is maintained. The top pointer is initialized to the lowest memory address in the stack.Each allocation request simply moves the pointer up by the requested number of bytes. The most-recently allocated block can be freed by simply moving the top pointer back down by the size of the block.

It's important to always roll the top pointer back to a point that lies at the boundary between two allocated blocks, because otherwise new allocations would overwrite the tail end of the top-most block.

 

Sample
 1 class StackAllocator
2 {
3 public:
4 //stack marker:Represents the current top of the
5 //stack. You can only roll back to a marker, not to
6 //arbitrary locations within the stack.
7 typedef int Marker;
8
9 //Constructs a stack allocator with the given total size.
10 explicit StackAllocator(int stackSize_Bytes);
11
12 //Allocates a new block of the given size from stack top.
13 void* alloc(int size_bytes);
14
15 //Returns a marker to the current stack top.
16 Marker getMarker();
17
18 //Rolls the stack back to a previous marker.
19 void freeToMarker(Marker marker);
20
21 //Clears the entire stack(rolls the stack back to zero)
22 void clear();
23 private:
24 //...
25 };

 

posted @ 2012-01-20 10:00  Cavia  阅读(323)  评论(0编辑  收藏  举报