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
)
For example, the comment on std.mem.Allocator.alloc()
says “Attempt to allocate exactly len
bytes aligned to 1 << ptr_align
”.
- 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.
- 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 
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 
- Why do we bit shift the pointer alignment?
- What’s up with the log2 alignment?
2 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