Why does not my program go into infinite loop when

2019-02-28 11:00发布

问题:

int main(){
   int i;
   int arr[4];
   for(int i=0; i<=4; i++){
      arr[i] = 0;
   }
   return 0;
}
  1. I watched a video on youtube of CS107(lecture 13) in which this example is shown and told why the above program will lead to infinite loop by showing memory diagrams. arr[4] goes out of bounds and should lead to an address where i is stored and changing the value of i back to 0 hence leading to infinite loop. But when I tried to run this on my mac using gcc compiler, for loop executed (checked by inserting printf) 5 times. i.e for the value of i = 0,1,2,3,4.

回答1:

When there is undefined behavior you can't expect a single or particular behavior. Anything could happen.
What said in that video is just one of many possibilities of undefined behavior and what you are getting is another possibility. One should not rely upon any particular behavior.



回答2:

first: it is undefined behaviour, anything can happen.

said this, you should try different optimization levels. one optimization can lead to loop-reduction:

for (i = 0; i <= 2; i++) arr[i] = 0;

can be reduced, because i and arr[i] are invariant in the scope of the loop, to

arr[0] = 0;
arr[1] = 0;
arr[2] = 0;

that would lead to your tested result.

Another thing to consider is the architecture which arranges the stack and places the items onto the stack (you cannot rely on the ordering of the items)