为什么在我的实现中所有数组都对齐为16个字节? [英] Why are all arrays aligned to 16 bytes on my implementation?

查看:142
本文介绍了为什么在我的实现中所有数组都对齐为16个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的简单代码如下所示

#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;
}

此代码的输出是

alignof(array_char):1

alignof(array_char): 1

alignof(array_float):4

alignof(array_float): 4

array_char的地址:0x7fff5e8ec580

address of array_char: 0x7fff5e8ec580

array_float的地址:0x7fff5e8ec570

address of array_float: 0x7fff5e8ec570

alignof运算符的结果符合预期,但是两个数组的实际地址与它们不一致.无论我尝试了多少次,地址始终都是16个字节对齐.

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.

我在具有Intel CORE i5第七代CPU的Ubuntu 16.04上使用gcc 5.4.0.

I'm using gcc 5.4.0 on Ubuntu 16.04 with Intel CORE i5 7th Gen CPU.

推荐答案

我发现补丁.

这似乎是GCC 6.4中修复的x86_64错误.

This seems to have been a bug for x86_64 fixed in GCC 6.4.

System V x86-64 ABI要求聚合类型(例如数组和struct)必须至少对齐16个字节(如果它们的大小至少为16个字节).根据ABI规范中的注释,这旨在促进SSE指令的使用.

The System V x86-64 ABI requires aggregate types (such as arrays and structs) 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似乎错误地将该规则应用于大小为16位(而不是字节)或更大的聚合.

GCC seem to have mistakenly applied that rule to aggregates of size 16 bits (instead of bytes) and larger.

我建议您将编译器升级到最新的GCC版本.

I suggest you upgrade your compiler to a more recent GCC version.

但这只是一个优化问题,而不是一个正确性问题.对变量进行更严格的对齐并没有什么错,并且(与上述SSE一样)过度对齐在某些情况下可能会带来性能上的好处,而这些情况会超过浪费的堆栈内存的成本.

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.

这篇关于为什么在我的实现中所有数组都对齐为16个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆