c - __attribute(对齐)测试。它有什么作用?

标签 c

我正在使用几个在线编译器来测试一个示例程序(供引用,ideone 中的一个和 tutorialspoint 中的那个) 程序是:

#include <stdio.h>
#include <stdint.h> 

uint8_t Array[5]__attribute((aligned(32)));
uint8_t Array2[5]__attribute((aligned(8)));
static uint8_t Array3[5]__attribute((aligned(8)));
static uint8_t Array4[5]__attribute((section("bbs"),aligned(32)));


int main()
{
    printf("%p %p %p %p %p \n", &Array[0], &Array[1], &Array[2], &Array[3],&Array[4]);
    printf("%p %p %p %p %p \n", &Array2[0], &Array2[1], &Array2[2], &Array2[3],&Array2[4]);
    printf("%p %p %p %p %p \n", &Array3[0], &Array3[1], &Array3[2], &Array3[3],&Array3[4]);
    printf("%p %p %p %p %p \n", &Array4[0], &Array4[1], &Array4[2], &Array4[3],&Array4[4]);

    return 0;
}

结果举例

0x2aff9175b0a0 0x2aff9175b0a1 0x2aff9175b0a2 0x2aff9175b0a3 0x2aff9175b0a4 
0x2aff9175b080 0x2aff9175b081 0x2aff9175b082 0x2aff9175b083 0x2aff9175b084 
0x2aff9175b068 0x2aff9175b069 0x2aff9175b06a 0x2aff9175b06b 0x2aff9175b06c 
0x2aff9175b040 0x2aff9175b041 0x2aff9175b042 0x2aff9175b043 0x2aff9175b044 

我可以看到对齐似乎对数组元素的存储位置没有影响。对齐实际上做了什么? (我是阅读了 here 中的解释后问的,我没听清楚。)

最佳答案

描述了对齐属性here in the GNU Compiler documentation .

它是这样说的:

This attribute specifies a minimum alignment for the variable or structure field, measured in bytes.

这意味着您将设置最小对齐方式,但数组的开头。数组的其余部分保证是连续的,这意味着后面的地址取决于示例 uint8_t 中的类型。如果数组起始地址位于 0x2aff9175b0a0 就像您的情况一样,下一个地址必须在 0x2aff9175b0a1 之后的 1 个字节(0xa0 --> 0xa1 ).

解释你的例子:

Alignment 32 beginning at: 0x2aff9175b0a0 --> 0xa0 = 160 = 32 * 5
Alignment 8  beginning at: 0x2aff9175b080 --> 0x80 = 128 = 8  * 16
Alignment 8  beginning at: 0x2aff9175b068 --> 0x68 = 104 = 8  * 13
Alignment 32 beginning at: 0x2aff9175b040 --> 0x40 = 64  = 32 * 2

如您所见,数组开头的对齐方式如您所愿。您可以增加对齐并再次查看地址。但也要考虑:

Note that the effectiveness of aligned attributes may be limited by inherent limitations in your linker. On many systems, the linker is only able to arrange for variables to be aligned up to a certain maximum alignment.

此外,如果您使用 printf() 打印带有 %p 的地址,那么也将地址转换为 void*,因为除了其中一些之外,指针类型不需要具有相同的表示形式。这个事实也是explained here .

关于c - __attribute(对齐)测试。它有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44668213/

相关文章:

c - Valgrind 无效释放,内存泄漏

c - C中的默认函数参数

c - 这个数学舍入函数是如何工作的?

在Linux中从一张图像更新创建电影

.net - Linq 查询从该 XML 解析/获取内容 (WSDL)

c - C语言如何读取scanset中的空格

c - google protocol buffer wire type 起始组和结束组用法

c - 反转数组而不使用第二个数组。 (C语言)

c - 内函数,无法定义 (C)

c - 为什么 tm_mday 从 1 开始,而 struct tm 的所有其他元素都从 0 开始?