问题
My very simple code shows below
#include <iostream>
#include <stdalign.h>
int main() {
char array_char[2] = {'a', 'b'};
float array_float[2] = {1, 2};
std::cout << "alignof(array_char): " << alignof(array_char) << std::endl;
std::cout << "alignof(array_float): " << alignof(array_float) << std::endl;
std::cout << "address of array_char: " << (void *) array_char << std::endl;
std::cout << "address of array_float: " << array_float << std::endl;
}
The output of this code is
alignof(array_char): 1
alignof(array_float): 4
address of array_char: 0x7fff5e8ec580
address of array_float: 0x7fff5e8ec570
The results of alignof
operator is under expectation, but the real addresses of the two arrays are not consistent with them. No matter how many times I tried, the addresses are always 16 bytes aligned.
I'm using gcc 5.4.0 on Ubuntu 16.04 with Intel CORE i5 7th Gen CPU.
回答1:
I have found this patch.
This seems to have been a bug for x86_64 fixed in GCC 6.4.
The System V x86-64 ABI requires aggregate types (such as arrays and struct
s) to be aligned to at least 16 bytes if they are at least 16 bytes large. According to a comment in the ABI specification this is meant to facilitate use of SSE instructions.
GCC seem to have mistakenly applied that rule to aggregates of size 16 bits (instead of bytes) and larger.
I suggest you upgrade your compiler to a more recent GCC version.
This is however only an optimization issue, not a correctness one. There is nothing wrong with stricter alignment for the variables and (as with the mentioned SSE) overalignment may have performance benefits in some situations that outweight the cost of the wasted stack memory.
来源:https://stackoverflow.com/questions/59074271/why-are-all-arrays-aligned-to-16-bytes-on-my-implementation