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

前端 未结 2 1546
小蘑菇
小蘑菇 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.

    0 讨论(0)
  • 2021-01-05 06:44

    You might to google "speculative reading". As soon as an address is formed, it may be smart for the cache architecture to bring the corresponding dataline into cache. Normally, this should be harmless, but if you're significantly out of bounds (e.g. onto the next page) this might no longer be true.

    0 讨论(0)
提交回复
热议问题