1

I'm currently working on a modding library for a particular game, and I have come across a part of the menu system that I can't figure out the purpose of.

The expression in question is this:

unsigned num = ((n + 1) * 4) / 3 + 3;

The game then goes on to use the value to allocate space for menu item structures:

void *newItemStorage = allocate(num * 0x18);

// 0x18 = sizeof(menu item structure)

n is the number of menu item structures there are currently, and the code containing this maths is used to allocate space for more structures when there is not currently enough (the old array is copied into the new space with memcpy).

From what I can tell, this system must be allocating more space than it needs so that fewer reallocations need to happen in the future. However, I don't see why this particular formula must be used to work out the space. The game stores num and only reallocates again when num < n + 1.

I actually graphed the formula when I was working out what it did, so here is that graph. (I used floor to try to simulate integer division.) One of the parts I find most confusing is the fact that num is in groups of three:

Starting at n = 0 and increasing by 1 yields: 4, 5, 7, 8, 9, 11, 12, 13.

If this is some system for preallocating memory, why is it being done like this? If not, what is the system doing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.