c – 即使指针从未被解除引用,如何在三个过去的指针中发生硬件陷阱?
作者:互联网
Herb Sutter在November 1, 2005 C++ column年写道……
int A[17];
int* endA = A + 17;
for( int* ptr = A; ptr < endA; ptr += 5 )
{
// ...
}
[O]n some CPU architectures, including
current ones, the aforementioned code
can cause a hardware trap to occur at
the point where the three-past-the-end
pointer is created, whether that
pointer is ever dereferenced or not.
CPU模式如何陷阱?关于什么 …
int A[17];
// (i) hardware will trap this ?
int *pUgly = A + 18;
// (ii) hardware will trap this, too?
int *pEnd = A + 17;
++pEnd;
// (iii) will this fool it?
int *precious = A + 17;
unsigned long tricksy = reinterpret_cast<unsigned long>(precious) ;
++tricksy;
int *pHobbits = reinterpret_cast<int *>(tricksy);
额外问题:“一些当前的CPU体系结构”这个短语是否应该被理解为仅仅指代运输产品,或者它是否包含虚构的体系结构,如果它们被描述或暗示的虚构作品具有最近的出版日期?
解决方法:
指针操作依赖于实现.
可能发生在某些平台上仅允许特定寄存器存储指针值(仅特定寄存器可用作索引寄存器),并且立即检查由非特权程序代码写入此寄存器的值是否为有效地址.在这种情况下,如果指针值对应于程序的地址空间中不存在的地址,则肯定会发生硬件陷阱.
如果是这种情况,编译器未优化的任何代码都会为指针分配新值,这可能会导致陷阱.
标签:pointer-arithmetic,c,cpu-architecture,hardware-traps 来源: https://codeday.me/bug/20191006/1862726.html