C++ Custom Memory Allocation

Started by
5 comments, last by Tanner Van De Walle 6 years, 4 months ago

So I was looking for a concrete example of dynamic memory allocation for game engine design, as the book "Game Engine Architecture" by Jason Gregory goes into a little detail about how allocating memory with 1 malloc() usage and then filling it with data instead of overusing malloc() which would slow down the entire engine. I came across this full explanation with source code examples:
 

My question lies in the 2nd portion of the topic of the aligned allocation portion. He is using reinterpret_cast(address), but I get an error by not having "<type-name-here>" before the "(address)". Is it supposed to be "reinterpret_cast<u8>(address)"? And is "<uint8_t>" the same thing, because I couldn't find the header file where u8 was defined.

So the code would look like this:
 


inline void* alignForward(void* address, uint8_t alignment)
{
return (void*)( ( reinterpret_cast<uint8_t>(address) + static_cast<uint8_t>(alignment-1)) & static_cast<uint8_t>(~(alignment-1)) );
}

What exactly is "reinterpret_cast<u8>(address)" doing? And the same for static_cast? I've never used those keywords before. Thank you for any help that can be provided :)

Advertisement

These types of questions are generally easy to search in your favorite search engine.  For example, "C++ dynamic_cast static_cast" gave me this result:

https://stackoverflow.com/questions/28002/regular-cast-vs-static-cast-vs-dynamic-cast

 

Additionally, it would seem that the article is not formatted properly.  The correct code should look something like:


inline void* alignForward(void* address, u8 alignment) {
	return (void*)(
		(reinterpret_cast<u8*>(address) + static_cast<u8>(alignment-1)) &
		static_cast<u8>(~(alignment-1))
    );
}

 

Ok, thank you. I wasn't sure which type I should reinterpret_cast for the address part, I assumed the static_cast was for u8.

I could certainly be wrong, but shouldn't the reinterpret_cast be to size_t instead of u8* ? Otherwise it seems like you would be truncating your address to only 8 bits.

38 minutes ago, Tanner Van De Walle said:

I could certainly be wrong, but shouldn't the reinterpret_cast be to size_t instead of u8* ? Otherwise it seems like you would be truncating your address to only 8 bits.

It's a pointer to a u8 value, not the actual value itself. The pointer is still going to be 32 or 64 bits, depending on the architecture. You need to cast it to a u8 pointer to have the pointer arithmetic treat it as a byte array, which is obviously what you want when allocating memory.

That makes sense (not sure how got turned around about the size of the u8* last night lol), but you can't do a bitwise AND on a pointer anyway, as far as I'm aware.

This topic is closed to new replies.

Advertisement