内存对齐

一 内存形式
编程者看内存的方式
在这里插入图片描述
cpu看内存的方式
在这里插入图片描述

二 内存不对齐的弊端

If you don’t understand and address alignment issues in your software,
the following scenarios, in increasing order of severity, are all possible:

1 Your software will run slower.
2 Your application will lock up.
3 Your operating system will crash.
4 Your software will silently fail, yielding incorrect results.

三 内存对齐好处
1 平台原因(移植原因):不是全部的硬件平台都能訪问随意地址上的随意数据的;某些硬件平台仅仅能在某些地址处取某些特定类型的数据,否则抛出硬件异常。

2 性能原因:经过内存对齐后,CPU的内存訪问速度大大提升。

四 内存访问粒度
本质是cpu读取是按块读取,块的大小分为1Byte, 2Byte, 4Byte, 8Byte, 16Byte, 32Byte等,这即是内存访问粒度

your computer’s processor does not read from and write to memory in byte-sized chunks. Instead, it accesses memory in two-, four-, eight- 16- or even 32-byte chunks. We’ll call the size in which a processor accesses memory its memory access granularity.

假设需要取四字节长度数据,看一下不同访问粒度下的访问次数

1 单字节访问粒度
在这里插入图片描述
无论是数据是对齐,还是非对齐方式,cpu都要执行4次访问

2 双字节访问粒度
在这里插入图片描述
对齐方式,访问需要两次,非对齐方式,访问需要3次

3 四字节内存访问粒度
在这里插入图片描述
对齐方式,访问需要一次,非对齐方式访问需要2次

五 结构体
结构体的内存对齐,相比更复杂一下,成员变量的顺序不同,对齐后占用的内存大小也有区别,对齐是使占用空间变大。

void Munge64( void ∗data, uint32_t size ) {
typedef struct {
    char    a;
    long    b;
    char    c;
}   Struct;

What is the size of this structure in bytes? Many programmers will answer “6 bytes.” It makes sense: one byte for a, four bytes for b and another byte for c. 1 + 4 + 1 equals 6. Here’s how it would lay out in memory:
在这里插入图片描述

However, if you were to ask your compiler to sizeof( Struct ), chances are the answer you’d get back would be greater than six, perhaps eight or even twenty-four. There’s two reasons for this: backwards compatibility and efficiency.

First, backwards compatibility. Remember the 68000 was a processor with two-byte memory access granularity, and would throw an exception upon encountering an odd address. If you were to read from or write to field b, you’d attempt to access an odd address. If a debugger weren’t installed, the old Mac OS would throw up a System Error dialog box with one button: Restart. Yikes!

So, instead of laying out your fields just the way you wrote them, the compiler padded the structure so that b and c would reside at even addresses:

在这里插入图片描述
六 总结
内存对齐本身对程序员来说是透明的,即程序员该取变量就取变量,该存就存,编译程序时编译器会把变量按本身的平台进行对齐。
并且,现在的CPU都很高级,很多CPU,ARM 7以上应该也支持内存不对齐访问

参考文档
1 https://developer.ibm.com/articles/pa-dalign/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值