C结构的内存布局? [英] C struct memory layout?

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

问题描述

我有C#的背景。非常新手到像C低级语言。

I have C# background. Very newbie to low level language like C.

在C#中,结构体的内存默认情况下,奠定了由编译器。编译器可以重新排序的数据字段或隐场之间垫附加位。所以我必须指定一些特殊的属性来覆盖这个行为进行精确的布局。

In C#, struct's memory laid out by compiler by default. 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.

据我所知,C不会重新排序或默认对齐结构的内存布局。但我听说有一个小例外,非常难找。

AFAIK, C does not reorder or align memory layout of a struct by default. But I heard there's a little exceptions which 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包允许控制填充和它留给程序员遵守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的每一个的非位字段构件
  结构或联合对象对齐
  以实现定义的方式
  适合其类型。

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天全站免登陆