Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test the pointers using relational operator in for loop

Tags:

arrays

c

pointers

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?

like image 862
Ashish Rawat Avatar asked May 12 '13 16:05

Ashish Rawat


1 Answers

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.

like image 81
Eric Postpischil Avatar answered Sep 27 '22 21:09

Eric Postpischil