什么是错位的指针? [英] What is a misaligned pointer ?

查看:235
本文介绍了什么是错位的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在下面的行,我们正在试图写入到一个无效的内存位置。但是,这实际上是一个不对齐指针也。有人可以解释什么是错位的指针又是怎样以下未对齐的指针?

  *(INT *)为0xffffffff = 0xbad;
 

解决方案

许多架构有一个概念叫的调整的,其中硬件的设计上是字大小的倍数的地址进行操作。例如,在32位处理器,对象可能被对准以32位边界(4字节),和在64位处理器,对象可能被排列为64位边界(8字节)。对准指针是一个指向一个地址的字的大小的倍数,和未对齐的指针是一个不是指向一个地址是这样的字大小的倍数。

在大多数架构,读取或写入未对齐的指针患有某种形式的处罚。在某些处理器,这样做会导致总线错误,这通常是立即终止程序。在其他国家,如X86,未对齐的读取和写入操作是合法的,但遭受性能损失是由于硬件的结构。

在你的code, 0xBAD = 2989 很可能不对齐,因为它不是一个多最常见的字长,并且你写指针也可能没有对齐。

希望这有助于!

I understand that in the following line we are attempting to write to an invalid memory location. But this is actually a misaligned pointer also. Can someone explain what is a misaligned pointer and how is the following misaligned pointer ?

*(int*)0xffffffff = 0xbad;

解决方案

Many architectures have a concept called alignment where the hardware is designed to operate on addresses that are multiples of the word size. For example, on a 32-bit processor, objects might be aligned to 32-bit boundaries (4 bytes), and on a 64-bit processor, objects might be aligned to 64-bit boundaries (8 bytes). An aligned pointer is one that points to an address that's a multiple of the word size, and an unaligned pointer is one that's not pointing to an address that's a multiple of the word size.

On most architectures, reading or writing unaligned pointers suffers some sort of penalty. On some processors, doing this causes a bus error, which usually terminates the program immediately. On others, such as x86, unaligned reads and writes are legal but suffer a performance penalty due to how the hardware is structured.

In your code, 0xBAD = 2989 is probably not aligned, since it's not a multiple of most common word sizes, and the pointer you write to is also probably not aligned.

Hope this helps!

这篇关于什么是错位的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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