gpt4 book ai didi

c - 了解 C 中的内存对齐约束和填充字节

转载 作者:太空狗 更新时间:2023-10-29 15:28:54 25 4
gpt4 key购买 nike

我有以下代码片段。

#include<stdio.h>
int main(){
typedef struct{
int a;
int b;
int c;
char ch1;
int d;
} str;
printf("Size: %d \n",sizeof(str));
return 0;
}

输出如下

Size: 20

我知道 structure 的大小大于 structure 组件大小的总和,因为添加了填充以满足内存对齐约束。我想知道如何决定必须添加多少字节的填充。它取决于什么?它取决于 CPU 体系结构吗?它也取决于编译器吗?我在这里使用 64 位 CPU 和 gcc 编译器。如果这些参数发生变化,输出将如何变化。

我知道 StackOverflow 上有类似的问题,但他们没有彻底解释这个内存对齐约束。

最佳答案

一般取决于架构的要求。负载超过 here , 但可以总结如下:

Storage for the basic C datatypes on an x86 or ARM processor doesn’t normally start at arbitrary byte addresses in memory. Rather, each type except char has an alignment requirement; chars can start on any byte address, but 2-byte shorts must start on an even address, 4-byte ints or floats must start on an address divisible by 4, and 8-byte longs or doubles must start on an address divisible by 8. Signed or unsigned makes no difference.

在您的情况下,可能会发生以下情况:sizeof(str) = 4(4 个字节用于 int)+ 4(4 个字节用于 int)+ 1(1 个字节用于 char)+ 7(3 个字节填充+ 4 字节用于 int) = 20

填充是为了让 int 位于一个 4 字节倍数的地址。这个要求来自 int 是 4 个字节长的事实(我对你正在使用的架构的假设)。但这会因架构而异。

关于c - 了解 C 中的内存对齐约束和填充字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30461997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com