Handmade Hero»Forums»Code
Oliver Marsh
193 posts / 1 project
Olster1.github.io
Explanation of Casey's platform allocate memory
Edited by Oliver Marsh on

Hi everyone, I was wanting to dig a bit deeper into memory allocation and wondered if anyone can explain Platform_allocate_memory in the latest handmade hero code?

I specifically don't understand what the underflow & overflow flags mean and their corresponding code paths.

https://github.com/HandmadeHero/cpp/blob/fc7e94b97a2759211a4a301a099beb3d818a36c2/code/win32_handmade.cpp#L1634

I thought I'd ask here before finding the video Casey mentions it. Thankyou šŸ™‚

Simon Anciaux
1337 posts
Explanation of Casey's platform allocate memory

The underflow and overflow checks are debug things. If you pass those flags, every allocation will be aligned on page boundary (the beginning of a page for underflow, the end of a page for overflow) and the previous (underflow) or next (overflow) page will be protected so that if you try to access the memory in those an exception will be triggered.

You can do that to be sure that when you allocate some memory, you don't write past it's end or before it's beginning (if you allocate 64 bytes VirtualAlloc still gives you a page of memory, so if you write outside those 64 bytes it's valid but probably not what you wanted).

Note that this will be slow and cost more memory as every single allocation in HMH would go through VirtualAlloc.

Oliver Marsh
193 posts / 1 project
Olster1.github.io
Explanation of Casey's platform allocate memory
Edited by Oliver Marsh on

Thanks Simon, that makes sense.

So for a 64byte thing it's quicker just going with HeapAlloc?

Simon Anciaux
1337 posts
Explanation of Casey's platform allocate memory

In handmade hero we use PushSize to allocate memory, and if the arena need to grow it will call VirtualAlloc with a "big" block so that VirtualAlloc isn't called often. So if you PushSize( 64...) it's fine. Just don't use the overflow and underflow flags.

From time to time (e.g. once a month), if you want to verify that you don't write outside of the memory you requested with PushSize you use the overflow/underflow flags, but only for the test.

You shouldn't use VirtualAlloc if you need to make a lot of small allocations. You generally use VirtualAlloc to allocate a "big" block of memory and use a custom allocator (like HMH arenas, and PushSize) on top of that. For information, VirtualAlloc always allocate with page size granularity (4096 bytes) and aligned on 64Kio (16 pages), so if you allocate 1 page, you "waste" 15 pages of address space.

I suppose HeapAlloc is better suited for smaller allocation, but I've never used it.