Suppose I have the for loop which store zeros in an array using pointers like this:
int *vp, values[5];
for(vp = &values[5-1]; vp >= &values[0]; vp--)
*vp = 0;
The book-Pointers on C said that there is a problem with this loop, because the comparison vp >= &values[0]
is undefined as it moved outside of the bounds of the array. But How?
This code is not safe even if old or exotic processor architectures are ruled out.
The optimizer in a compiler embeds many rules about the language. When it sees vp >= &values[0]
, where values
is an array, the optimizer is entitled to assume that vp
points to an array element or one beyond the array, because otherwise the expression is not defined by the C language.
The rules and mechanisms embedded in the optimizer may therefore decide that vp >= &values[0]
is always true, so it may produce code as if for (vp = &values[5-1]; ; vp--)
had been written. This results in a loop without a termination condition and further undefined behavior when *vp = 0
is evaluated with vp
pointing outside of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With