未对齐的内存访问是否总是会导致总线错误?
根据维基百科页面分段错误,可能会导致总线错误通过未对齐的内存访问。文章给出了如何触发总线错误的示例。在示例中,我们必须启用对齐检查才能看到总线错误。如果我们禁用这种对齐检查怎么办?
该程序似乎运行正常。我有一个程序经常访问未对齐的内存,并且被很多人使用,但没有人向我报告总线错误或其他奇怪的结果。如果我们禁用对齐检查,未对齐内存的副作用是什么?
平台:我正在开发 x86/x86-64。我还在 Mac 上使用“gcc -arch ppc”编译了我的程序,并且它运行正常。
According to the Wikipedia page Segmentation fault, a bus error can be caused by unaligned memory access. The article gives an example about how to trigger a bus error. In the example, we have to enable alignment checking to see the bus error. What if we disable such alignment checking?
The program seems to work properly. I have a program access unaligned memory frequently, and it is used by quite a few people, but no one reports bus errors or other weird results to me. If we disable alignment checking, what is the side effect of unaligned memory?
Platforms: I am working on x86/x86-64. I also tried my program by compiling it with "gcc -arch ppc" on a Mac and it works properly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
访问未对齐的内存可能会显着变慢(如,慢几倍)。
并非所有平台都支持未对齐访问 - 例如,x86 和 x64 支持,但 ia64 (Itanium) 不支持。
并非所有平台都支持未
编译器可以模拟未对齐的访问(例如,VC++ 对 ia64 上声明为
__unaligned
的指针执行此操作) - 通过插入额外的检查来检测未对齐的情况,并且分别加载/存储跨越对齐边界的对象部分。然而,这比原生支持它的平台上的未对齐访问还要慢。It may be significantly slower to access unaligned memory (as in, several times slower).
Not all platforms even support unaligned access - x86 and x64 do, but ia64 (Itanium) does not, for example.
A compiler can emulate unaligned access (VC++ does that for pointers declared as
__unaligned
on ia64, for example) - by inserting additional checks to detect the unaligned case, and loading/storing parts of the object that straddle the alignment boundary separately. That is even slower than unaligned access on platforms which natively support it, however.这在很大程度上取决于芯片架构。 x86 和 POWER 非常宽容,Sparc、Itanium 和 VAX 会抛出不同的异常。
It very much depends on the chip architecture. x86 and POWER are very forgiving, Sparc, Itanium and VAX throw different exceptions.
考虑一下我刚刚在 ARM9 上测试过的以下示例:
Consider the following example I have just tested on ARM9: