Looking for some explanation about why memory alignment matters

Hello! New person here. I’m also pretty new to systems programming in general.

In reading some of the std library code, i’ve come across a bunch of memory alignment-related stuff. I don’t quite get it.

I have read the blurb in the docs about it. But i am still unsure of what to do with that information. (i would link to it, but apparently new users are only allowed 2 links per post :laughing: )

For example, the comment on std.mem.Allocator.alloc() says “Attempt to allocate exactly len bytes aligned to 1 << ptr_align”.

  1. What does shifting the pointer alignment to the left by one give you? Why wouldn’t you want to “Attempt to allocate len bytes aligned to ptr_align” instead?

Another example is the code for allocating a fixed buffer.

  1. I’m not sure i get the “log2” alignment

Apologies if this isn’t the right place for such specific questions.

Thanks!

2 Likes

This should help with understanding alignment.

Once it clicks you’ll be able to reason from there, hopefully.

Sorry, that’s my lazy answer, but to be fair, I don’t think I’ve seen a clearer explanation :sweat_smile:

2 Likes

this is exactly what i’m looking for, links, more blurbs, talks etc… thank you! I’ll watch this in a bit and respond

2 Likes

That was an enlightening talk. He briefly touches on alignment and the examples of calculating the alignment and size were very helpful in terms of visualizing things. But i’m afraid it doesn’t answer my questions :confused:

  1. Why do we bit shift the pointer alignment?
  2. What’s up with the log2 alignment?
2 Likes
  1. It’s actually bit shifting 1 by the log2 alignment, which always gives you a power of two (1 << 10 == 1024 == 2^10)
  2. Alignment must always be a power of two so making alignment parameters take the log2 of the alignment and then reconstructing the actual alignment using bit shifting enforces the power-of-two-ness without any need for asserts/isPowerOfTwo checks. This is mostly a guess as to the reasoning but it’d make sense to me if this were the case.
4 Likes

Oooh i think you are right.

I’m also tossing in a couple of other breaking API changes while we’re at it:

alignment passed as a power of two instead of u29. To get the alignment, (1 << align_exp). This makes invalid alignments unrepresentable, and avoids the question of what data type to use for alignment, given that u29 will be changing soon.

4 Likes

And yea, clearly i didn’t the order in which the shift was happening thank you for clarifying.
This makes sense to me now !

4 Likes