How could one read and write past an array

Program Output:

#include <stdio.h> int main() { int size; printf("Enter the size of array: "); scanf("%d",&size); int b[size],i = 0; printf("Enter %d integers to be printed: ",size); while(i++ < size) { scanf("%d",&b[i]); printf("%d %d\n", i, b[i]); } return 0; } 

for size = 5 and input number:

 0 1 2 3 4 

there is

 1 0 2 1 3 2 4 3 5 4 

where the first column is for i and the second is for the elements of array b .
It is clear that i in the while(i++ < size) { increases to 1 before entering the loop. This cycle should store / print the value to / from b[1], b[2], b[3], b[4] , but not b[5] , since the cycle ends at i = 5 .
How does this code print the value of b[5] ?
I tested it for different size arrays and did not print any garbage value.

0
source share
3 answers

When reading and writing through an array, your program invokes undefined behavior. This does not mean that it should dump or print garbage values, it can pretend that it works fine. Apparently this is what happens in this case.

+2
source

In your loop, the condition i < size checked before i is increased. But, i increases before entering the body of the cycle, and not after it, therefore, in this case, you can access b[5] , since i will increase after checking i < size by i=4 . You do not want this, as this causes the program to behave undefined.

If you try to access an element in an array that does not exist, for example. array[size] , you get access to the next place in memory right after the array. In this case, you are lucky, but if this means that you are accessing a part of memory where your program is not allowed to do this, you will get a segmentation fault .

+1
source

you can use a for loop instead , whereas , instead of while(i++<size) you can use for(i = 0; i < size; i++) , which should solve your problem, my friend :)

+1
source

Source: https://habr.com/ru/post/1491458/


All Articles