Can someone help with my stack based allocator.
static char Stack[MAX_SIZE];
static char *top = &Stack[0];
class STACKED {
public:
static void *operator new(size_t size) {
//Add this context to the context stack.
void *Result;
assert( (top + size) <= &Stack[MAX_SIZE] );
Result = top;
top = top + align_sizeof(size);
return Result;
}
static void operator delete(void *p) {
//Its a stack, and delete only removes the top entry.
// So *p represents where to delete to.
top = (char *)p;
}
static size_t align_sizeof(size_t object_size) {
// TODO: Align objects.
return object_size;
}
};
1) Is the assert correct to detect if the stack will overflow?
2) align_sizeof() - Id like to align these objects for performance/bus issues. But I do not fully understand alignment. Can someone describe memory alignment, and suggest a formula to align the stack objects?
2a) My current thinking is to "roundup" the size of the object so that top is always aligned. Effectively allocating more memory than required (placing padding at the end).
3) I'm guessing I also have to align the static char Stack[MAX_SIZE] - How do I do this?
Thankyou!
P.S any other comments always welcome
A B Cget allocated in this order andBis destroyed beforeCand an objectDwithsizeof(D) > sizeof(B)is allocated?sizeis too large, the expressiontop + sizecauses undefined behaviour. So you should check thatStack + MAX_SIZE - top < size.