4

Alignment is defined in the Standard as follows:

An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.

However, this does not imply that such addresses are multiples of the alignment value. For instance, two double objects at addresses 0x01 and 0x09 satisfies the above definition.

Is it guaranteed somehow that an address of an object is a multiple of the alignment value for its type?

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93

2 Answers2

2

No it isn't.

Only a linear relationship, not a proportionality is guaranteed, but even then the alignment requirements could be relaxed in structure packing, for example

/*packed*/ struct s {double a; char b; double c;);

Note that nullptr does not even have to be the zero memory byte, virtual memory or otherwise.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • So even `alignas(8)` doesn't guarantee an address to be a multiple of 8? – Daniel Langr Jul 16 '18 at 08:13
  • @DanielLangr: I can't see anything in the standard that guarantees that. – Bathsheba Jul 16 '18 at 08:37
  • Me neither. Just the [cppreference.com](https://en.cppreference.com/w/cpp/language/alignas) gives the following example: `alignas(128) char cacheline[128]; // the array "cacheline" will be aligned to 128-byte boundary`. But it's not the Standard, of course. – Daniel Langr Jul 16 '18 at 08:39
  • 1
    @DanielLangr: But that still doesn't mean that the boundaries start from zero, if you get my meaning. – Bathsheba Jul 16 '18 at 08:40
0

For objects that are not struct or union members, the Standard does not define any means by which alignment could be observed, unless operations fail because of misalignment. If a platform can silently process objects with arbitrary alignment (though perhaps not as fast as objects that are correctly aligned), and if an implementation for that platform doesn't define uintptr_t or intptr_t, there would be no observable way by which failure to align standalone objects could be detected, and thus no requirement to actually align objects.

Most implementations would document ways of detecting pointer alignment, and should process alignment directives so they behave in a fashion consistent with their documentation. One could have a conforming implementation that did otherwise, just as one could have conforming-but-low-quality implementations do all sorts of weird goofy things, but quality implementations should refrain from such nonsense.

supercat
  • 77,689
  • 9
  • 166
  • 211