How could it be possible to read and write past the array

后端 未结 3 2023
一整个雨季
一整个雨季 2020-12-12 05:42

Output of the program:

#include 

int main()
{
    int size;

    printf(\"Enter the size of array: \");
    scanf(\"%d\",&size);

    i         


        
相关标签:
3条回答
  • 2020-12-12 06:18

    you could use a for cycle instead of a while so instead of while(i++<size)you could use for(i = 0; i < size; i++) that should solve your problem my friend :)

    0 讨论(0)
  • 2020-12-12 06:26

    By reading and writing past the array, your program invokes undefined behavior. It doesn't mean that it has to crash or print garbage values, it can pretend working fine. Apparently, that's what is happening in this case.

    0 讨论(0)
  • 2020-12-12 06:33

    In your loop, the condition i < size is checked before i is incremented. But, i is incremented before entering the body of the loop and not after it, so it is possible to access b[5] in this case, as i would be incremented after checking i < size with i=4. You do not want that, as this causes undefined program behavior.

    If you try to access an element in the array which does not exist, e.g. array[size], you are accessing the next spot in the memory right after the array. In this case you are lucky, but if this meant you were accessing a part of the memory where your program isn't allowed to do so, you'd get a segmentation fault.

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