c - What exactly happens if I declare a 10 elements array and try to access a bigger position within it? -


it happened me. bug. set 5 element array , position variable scroll through index:

int matematica[5]; int pos = 0; 

and had loop working ok. this:

while (pos < 5) {     printf("entre com o número da matrícula %dº aluno: \n", pos+1);     scanf("%d", &num);     if (num != 35)         matematica[pos] = num;     pos++; } 

everything working charm. after that, had same 150 positions, changed while loop while (pos < 5) while (pos < 150) forgot same array. happened object of question itself. program didn't crash or something, happened printf , scanf statements run bit more 5 times stops (sometimes 8 times, 7...)

why happens. of course fixed later, still can't grasp logic behind bug.

the c standard says triggers undefined behavior,

anything happen.

  • it appear work "correctly"
  • it terminate error code.
  • it unexpected.

this type of bug called buffer overrun, , these can lead arbitrary code execution (which special subclass of "something unexpected")

in example pos occupies same memory matematica[5], (because (all?) compilers pack global variables fields in struct) depending on number enter in sixth place loop may stop or continue, negative numbers cause interesting results.


Comments