Search code examples
c++stacknew-operatordelete-operator

Custom Stack Allocator, override Delete


I want to create a global stack in my application, and to place certain objects on to this stack. These objects are not of a fixed size.

I currently have;

static char contextStack[CONTEXT_MAX_SIZE];
static char *top = &contextStack[0];

and I override the new operator of a base class which is inherited

static void *operator new(size_t size) {
  void *Result;
  Result = top;
  top = top + size;
  return Result;
};

The problem is how would I implement the delete operator to pop it off the stack? It doesn't tell me how big the item was? Do I have to store the size of each entry in an array?

(p.s) The last one created is always the first to be deleted. And conforms to a stack.


Solution

  • There are different options to handle the memory in this case. If you are returning memory in increasing order (which seems to be the case), you do not need to remember the size. The last memory block allocated will be from allocated pointer to top, and you don't even need to perform the arithmetic, as setting top to be the pointer passed to delete will suffice.

    If you were allocating memory in descending order (as is common in a stack) you can store the size in the stack itself. Perform the pointer arithmetic to obtain the new Result (top - requested_size), then decrement sizeof(int), store the size there and set the top pointer to be that pointer.

    You should be aware of alignment restrictions in your platform, and even if the platform allows unaligned access to all data types, you might want to still align the data for performance (and thread-safety) reasons.