Sign in to follow this  

C++ alignment

This topic is 4287 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have been doing some research into memory managers. While reading through an already existing one, I came across the following line of code (comment mine):
//Result is the pointer where the new memory will be allocated, aligned according to Align (8 or 16). PTRINT is a typedef for long.
//Top is the last location that memory was allocated at.
BYTE* Result = (BYTE *)(((PTRINT)Top + (Align-1)) & ~(Align-1) );
And I am having trouble understanding it. I understand the code itself and I've worked out what the result would be with a fictional value for Top (I tried it with 32 and an Align of 16, shown below), but I don't understand why this returns an address aligned on either 8 or 16 byte boundaries.
Top 		= 0000000000000000000000000100000 (32)
Align - 1 	= 0000000000000000000000000001111 (15)
-------------------------------------------------------- +
Result	 	= 0000000000000000000000000101111 (47)
~(Align - 1) 	= 0000000000000000000000000000000 (15)
-------------------------------------------------------- &
Result		= 0000000000000000000000000000000 (0)
Does this look correct or am I completely misunderstanding something? EDIT: I'm not sure how to get the pretty code boxes, apologies.

Share this post


Link to post
Share on other sites
Quote:
Original post by 97
EDIT: I'm not sure how to get the pretty code boxes, apologies.


Use [ source ] for them.

The bitwise-and-of-bitwise-not is designed to "chop off" the lower part of the number:

  SOMEBINARYNUMBER
& 1111111111110000
--------------------
SOMEBINARYNU0000


Since U in the above example is the 16ths place, and all the digits left of it are multiples of that, it follows that since all the digits are multiples of 16, that the number itself will be divisible by 16 (in the case of addresses, this is equivilant to "aligned to 16 byte boundries")

The addition is to cause the whole shebang to round up instead of down (since rounding down would put the address before the allocated block of memory, instead of in the middle of it)

HTH

Share this post


Link to post
Share on other sites
Ahhh, I see my error in thinking now. I thought that the ~(Align-1) would flip all the bits to 0, but ofcourse the bits that are already 0 will be flipped to 1. Doh.

Thanks for the explanation, it makes sense now.

Share this post


Link to post
Share on other sites
Sign in to follow this