I know what aligning a pointer means. I believe "size" here means the size of the memory to be occupied by the object in which the pointer is pointing to. But you're also given an "alignment" variable. What is the meaning of this variable? In this context, is it simply the value in which you want the address to be a multiple of? e.g., 4 (which I think is typical)?
Asked
Active
Viewed 415 times
0
-
1Decent read: https://en.wikipedia.org/wiki/Data_structure_alignment – NathanOliver Aug 23 '21 at 20:00
-
1this might also help your understanding: https://stackoverflow.com/questions/58435348/what-is-bit-padding-or-padding-bits-exactly – NathanOliver Aug 23 '21 at 20:02
1 Answers
1
In this context, is it simply the value in which you want the address to be a multiple of? e.g., 4
Yes.
And to align a pointer, you round the unaligned address up to the nearest multiple. There is a standard function for this purpose in the C++ standard library: std::align
. The function can also be used to test whether a pointer is aligned.

eerorika
- 232,697
- 12
- 197
- 326
-
@user5965026 Let's say you are given memory range from address 6...32. This is given to you as a pointer to the first address that is 6 and the total size. You need to create an object there of a type that has the size 16 and alignment of 4. Where within that memory could you create such object? – eerorika Aug 23 '21 at 20:58
-
@user5965026 Answer: You cannot create the object in the address 6 because that address isn't aligned to the 4 byte boundary. You also cannot create the object in address 4 because that is outside of the memory range you were given. You can create the object in the address 8 because that is aligned and the object fits within the memory area. 6 roudned up to nearest multiple of 4 is 8. – eerorika Aug 23 '21 at 20:58
-
Understood. I actually deleted my question because I got some concepts mixed up earlier :). So to round it up a given pointer, say `ptr`, it seems you just do something like `(ptr + alignment - 1) / alignment * alignment)`? – user5965026 Aug 23 '21 at 21:27
-
@user5965026 That won't work with pointers because you cannot divide nor multiply pointers. And if it's a pointer of the object type, then addition works in increments of size. – eerorika Aug 23 '21 at 21:30
-
Oh I see. If `ptr` was `int *`, it seems I could get it to work by using `((intptr_t)ptr + alignment - 1) / alignment * alignment)`. How would you do it for a custom data type without the use of `std::align`? – user5965026 Aug 23 '21 at 21:33
-
@user5965026 The problem with casting pointers to integers is that standard doesn't technically guarantee anything else other than converting the same integer back to the same pointer type produces the same value. There's no guarantee that aligning the integer would produce an aligned pointer. That's why I wouldn't use anything other than `std::align` to do it. – eerorika Aug 23 '21 at 21:43