c - 关于 C struct packing 有什么保证吗?

标签 c packing

关于在 C 中打包结构是否有任何保证?

举个例子,假设sizeof(double) == 8,是否保证sizeof(struct { double x, y; }) == 16

我知道这个问题背后的意图与严格的别名规则冲突,因此假设禁用了严格的别名,例如对于带有 -fno-strict-aliasing 的 gcc。

为了避免任何进一步的推测:目的是了解结构与其显式打包的对应结构的兼容性。请注意,即使在以下情况下,别名也是相关的:Are C-structs with the same members types guaranteed to have the same layout in memory? .无需担心我想要访问单个字节。

最佳答案

C 标准关于结构打包的唯一规定是 struct 的开头不能存在填充。它不保证字段之间或末尾的填充。

C standard 的第 6.7.2.1 节说了以下关于结构的内容:

15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

...

17 There may be unnamed padding at the end of a structure or union.

也就是说,大多数实现往往与结构的打包方式相当一致。大小为 n 字节的非结构变量(或此类变量的数组)往往从 n 字节边界开始。结构中的结构将倾向于根据其子字段的对齐方式进行对齐。

The Lost Art of C Structure Packing对此进行了更详细的介绍。

关于c - 关于 C struct packing 有什么保证吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47662791/

相关文章:

c - 寄存器如何作为汇编中的参数工作?

C 位域内存使用

不能在 C 中使用延迟/ sleep 函数

python - 如何打包我的 Python 3 程序以便我可以发布它

python - Python 中的元组声明

c# - 使用 P/Invoke Interop Assistant 时的数据结构和堆栈损坏

c - 空指针是否间接指向数组类型 UB?

c - __libc_start_main 中的调试函数

Javascript 打包有很多限制,寻找简单的解决方案

algorithm - 文本打包算法