为什么赞成数据结构对齐? [英] Why favour data structure alignment?

查看:87
本文介绍了为什么赞成数据结构对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结构的每个成员的类型通常具有默认对齐,即每个结构成员在预定边界上对齐。
因此,在以下wiki示例中执行填充:

The type of each member of the structure usually has a default alignment i.e.each structure member is aligned on a pre-determined boundary. For this reason the padding is performed in the following wiki example:

struct MixedData
{
    char Data1;
    short Data2;
    int Data3;
    char Data4;
};



struct MixedData  /* After compilation in 32-bit x86 machine */
{
    char Data1; /* 1 byte */
    /* 1 byte for the following 'short' to be aligned on a 2 byte boundary 
assuming that the address where structure begins is an even number */
    char Padding1[1];
    short Data2; /* 2 bytes */
    int Data3;  /* 4 bytes - largest structure member */
    char Data4; /* 1 byte */
    char Padding2[3]; /* 3 bytes to make total size of the structure 12 bytes */
};

应该保留对齐的(实际)原因是什么?

What is the (practical) reason that alignment should be preserved?

推荐答案

未对齐的读取和写入通常需要CPU从内存中获取两个相邻的字(而不是一个),并应用一些额外的逐位算术指定的操作。

Unaligned reads and writes usually require the CPU to fetch the two adjacent words from memory (instead of just one) and to apply some additional bitwise arithmetic in order to perform the designated operation properly.

一些架构,如x86将允许它的性能成本。其他架构(最明显的是ARM)将引发异常(通常导致用户进程的 SIGBUS 信号),甚至将地址round到最接近的边界可能会导致一些非常讨厌的错误。

Some architectures, like x86 will allow it at a performance cost. Other architectures (most notably ARM), will either raise an exception (usually resulting in a SIGBUS signal for a user process) or even "round" the address to the closest boundary which could result in some very nasty bugs.

这篇关于为什么赞成数据结构对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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