Why does this for loop exit on some platforms and not on others?

前端 未结 14 2735
执念已碎
执念已碎 2020-12-12 09:00

I have recently started to learn C and I am taking a class with C as the subject. I\'m currently playing around with loops and I\'m running into some odd behaviour which I d

14条回答
  •  失恋的感觉
    2020-12-12 09:42

    The bug lies between these pieces of code:

    int array[10],i;
    
    for (i = 0; i <=10 ; i++)
    
    array[i]=0;
    

    Since array only has 10 elements, in the last iteration array[10] = 0; is a buffer overflow. Buffer overflows are UNDEFINED BEHAVIOR, which means they might format your hard drive or cause demons to fly out of your nose.

    It is fairly common for all stack variables to be laid out adjacent to each other. If i is located where array[10] writes to, then the UB will reset i to 0, thus leading to the unterminated loop.

    To fix, change the loop condition to i < 10.

提交回复
热议问题