C 中的结构体内存布局
我有 C# 背景。我对 C 这样的低级语言来说是个新手。
在 C# 中,struct
的内存默认由编译器布局。编译器可以重新排序数据字段或隐式在字段之间填充附加位。因此,我必须指定一些特殊属性来覆盖此行为以获得精确的布局。
AFAIK,默认情况下,C 不会重新排序或对齐 struct
的内存布局。不过,我听说有一个很难找到的例外。
C 的内存布局行为是什么?什么应该重新排序/对齐,什么不应该?
I have a C# background. I am very much a newbie to a low-level language like C.
In C#, struct
's memory is laid out by the compiler by default. The compiler can re-order data fields or pad additional bits between fields implicitly. So, I had to specify some special attribute to override this behavior for exact layout.
AFAIK, C does not reorder or align memory layout of a struct
by default. However, I heard there's a little exception that is very hard to find.
What is C's memory layout behavior? What should be re-ordered/aligned and not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它是特定于实现的,但实际上规则(在没有#pragma pack 等的情况下)是:
sizeof(T)
字节的对齐。因此,给定以下结构:
ch1
位于偏移量 0 处s
位于偏移量 2ch2
位于偏移量 4,紧接在 s 处ll
在偏移量 8 处i
位于偏移量 16,紧接在 ll所以
sizeof(ST)
是 24。通过重新排列成员以避免填充,可以将其减少到 16 字节:
It's implementation-specific, but in practice the rule (in the absence of
#pragma pack
or the like) is:sizeof(T)
bytes.So, given the following struct:
ch1
is at offset 0s
at offset 2ch2
is at offset 4, immediately after sll
at offset 8i
is at offset 16, right after llSo
sizeof(ST)
is 24.It can be reduced to 16 bytes by rearranging the members to avoid padding:
在 C 中,编译器可以为每个基本类型指定某种对齐方式。通常,对齐方式是类型的大小。但这完全是特定于实现的。
引入填充字节,以便每个对象都正确对齐。不允许重新排序。
可能每个远程现代编译器都实现了#pragma pack,它允许控制填充并将其留给程序员以遵守 ABI。 (不过,这完全是非标准的。)
来自 C99 §6.7.2.1:
In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.
Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.
Possibly every remotely modern compiler implements
#pragma pack
which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)From C99 §6.7.2.1:
您可以首先阅读数据结构对齐维基百科文章,以更好地了解数据对齐。
来自维基百科文章:
来自 GCC 文档的 6.54.8 Structure-Packing Pragmas:
You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.
From the wikipedia article:
From 6.54.8 Structure-Packing Pragmas of the GCC documentation: