• 15
• 15
• 11
• 9
• 10

# C++ alignment

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

## 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 on other sites
Quote:
 Original post by 97EDIT: 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