开发者社区 问答 正文

联合体的内存问题

screenshot
求高人指点

展开
收起
杨冬芳 2016-05-30 16:40:53 1862 分享 版权
1 条回答
写回答
取消 提交回答
  • IT从业

    构体(struct)

    简单来说,结构体的数据成员在内存中的顺序是确定的,但是每个数据成员前后有可能插入一定数量的位(bit)来保证内存是对齐的。如下图所示:
    screenshot
    每个方格右上角的数字即变量的起始地址偏移量。

    From C99 §6.7.2.1:

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

    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.

    联合体(union)

    简单来说,联合体中的所有成员的地址都是相同的。如下图所示:
    screenshot
    三个变量的起始地址偏移量都是 0。

    From the C99 standard §6.7.2.1:

    14 The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa.

    参考

    •C struct memory layout - Stack Overflow

    •Memory layout of union of different sized member - Stack Overflow

    •ELF ABI §3.1

    2019-07-17 19:20:45
    赞同 展开评论
问答标签:
问答地址: