Why does not my program go into infinite loop when array out of bounds occur in C

折月煮酒 提交于 2019-12-04 05:43:33

问题


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)



来源:https://stackoverflow.com/questions/32185385/why-does-not-my-program-go-into-infinite-loop-when-array-out-of-bounds-occur-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!