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
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
.