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

前端 未结 2 1205
遥遥无期
遥遥无期 2021-01-27 03:38
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(l
相关标签:
2条回答
  • 2021-01-27 03:57

    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.

    0 讨论(0)
  • 2021-01-27 04:23

    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)

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