How does a hardware trap in a three-past-the-end pointer happen even if the pointer is never dereferenced?

前端 未结 2 1544
小蘑菇
小蘑菇 2021-01-05 06:04

In his November 1, 2005 C++ column, Herb Sutter writes ...

int A[17];
int* endA = A + 17;
for( int* ptr = A; ptr < endA; ptr += 5 )
{
  // ...
}
         


        
2条回答
  •  醉梦人生
    2021-01-05 06:38

    Pointer operations are implementation-dependent.

    It can happen that on some platform only specific registers are allowed for storing pointer values (only specific registers can serve as index registers) and the value written into such register by a non-priviledged program code is immediately checked for being a valid address. In this case if the pointer value corresponds to an address not present in the address space of the program the hardware trap will certainly occur.

    If that's the case any code not optimized out by the compiler that assigns a new value to a pointer can potentially cause a trap.

提交回复
热议问题