C中的结构内存布局 [英] Struct memory layout in C

查看:71
本文介绍了C中的结构内存布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有C#背景.我是C之类的低级语言的新手.

I have a C# background. I am very much a newbie to a low-level language like C.

在C#中,默认情况下,struct的内存由编译器布置.编译器可以重新排序数据字段或隐式填充字段之间的其他位.因此,我必须指定一些特殊属性来覆盖此行为,以获取准确的布局.

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默认情况下不会重新排序或对齐struct的内存布局.但是,我听说很难找到一个小例外.

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.

C的内存布局行为是什么?什么应该重新排序/对齐而不是?

What is C's memory layout behavior? What should be re-ordered/aligned and not?

推荐答案

在C语言中,允许编译器为每种原始类型指定某种对齐方式.通常,对齐方式是类型的大小.但这完全是特定于实现的.

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.

可能每个远程的现代编译器都实现#pragma pack,它允许对填充进行控制并将其留给程序员以符合ABI. (不过,这绝对是非标准的.)

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.)

根据C99§6.7.2.1:

From C99 §6.7.2.1:

12 a的每个非位字段成员 结构或并集对象对齐 以实现定义的方式 适合其类型.

12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

13个 结构对象,非位域 成员和单位 位域所驻留的地址 他们的顺序增加 被宣布.指向结构的指针 适当转换后的对象指向 它的初始成员(或如果该成员 是位字段,然后到单位 它所在的位置),反之亦然. 可能有一个未命名的填充 结构对象,但不在其 开始.

13 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.

这篇关于C中的结构内存布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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