【问题标题】:Why struct size do not match with plain sum of item's sizes? [duplicate]为什么结构大小与项目大小的简单总和不匹配? [复制]
【发布时间】:2013-09-30 06:22:04
【问题描述】:

对于 C/C++ 结构,通常,最终结构的大小是其所有元素大小的简单总和,但在某些情况下这不是真的。

我正在研究为什么以下结构的大小不等于其所有成员的大小的技术答案(它必须是一个):

#include <iostream>

struct {
    int a;
    long b;
    char c;
} typedef MyStruct;

int main() {
    MyStruct sss;
    std::cout << "Size of int: " << sizeof(int) << std::endl << "Size of long: " << sizeof(long) << std::endl << "Size of char: " << sizeof(char) << std::endl;
    std::cout << "Size of MyStruct: " << sizeof(sss) << std::endl;
    return 0;
}

输出如下:

Size of int: 4
Size of long: 8
Size of char: 1
Size of MyStruct: 24

所以可以看出MyStruct的大小不是4+8+1 (13),而是24,但是为什么呢?

【问题讨论】:

  • 对齐。有更多关于此的问题有很好的答案。
  • 查一下struct padding的概念。

标签: c++ c padding memory-alignment


【解决方案1】:

因为 C 允许编译器在 struct 的元素之间添加填充,以提高生成的代码的性能。

当将多字节数据放置在可被数据大小整除的内存地址时,某些硬件允许更快地访问多字节数据。例如,当int 位于地址0x80040x8008 时,访问32 位int 可能比相同int 位于地址0x80030x8006 时快得多.该标准允许编译器调整struct 成员的偏移量以利用这种优化。

此外,在某些平台上,访问与内存空间不对齐的多字节值会导致错误:例如,从 68000 中的奇数地址读取 16 位 int架构触发总线错误。编译器知道这一点,他们会将未使用的空间添加到您的 struct,以便访问多字节字段不会触发错误。

【讨论】:

  • 只是为了符合底层架构(许多处理器不接受未对齐的内存访问,具体取决于访问的大小)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 2016-01-19
  • 2011-03-22
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多