I made some tests in VSC to check the behaviors of arrays. I´ve encountered in the output of one test the issue, that there was apparently happend undefined behavior despite the array element was defined proper, but just not initialized (with proper i mean the array element was defined with the array itself, not additionally over the bounds of the array which causes well-known undefined behavior).
Here is my code, and the output of it below it:
The issue is about the output of foo[4]
which is 8 instead of 0.
#include <stdio.h>
int main()
{
int foo[12];
int i;
foo[5] = 6;
foo[6] = 7;
foo[7] = 8;
foo[8] = 9;
foo[9] = 10;
foo[10] = 11;
foo[11] = 12;
for(i=0 ; i<=11 ; i++)
{
printf("foo[%d] = %d\n",i,foo[i]);
}
}
Output:
foo[0] = 0
foo[1] = 0
foo[2] = 0
foo[3] = 0
foo[4] = 8
foo[5] = 6
foo[6] = 7
foo[7] = 8
foo[8] = 9
foo[9] = 10
foo[10] = 11
foo[11] = 12
Thereafter i tried it else and wanted to see if foo[5]
might is influenced also, if i do not initialise it as well, but it wasn´t the case. foo[4]
still had the wrong value btw:
#include <stdio.h>
int main()
{
int foo[12];
int i;
// foo[5] = 6;
foo[6] = 7;
foo[7] = 8;
foo[8] = 9;
foo[9] = 10;
foo[10] = 11;
foo[11] = 12;
for(i=0 ; i<=11 ; i++)
{
printf("foo[%d] = %d\n",i,foo[i]);
}
}
Output:
foo[0] = 0
foo[1] = 0
foo[2] = 0
foo[3] = 0
foo[4] = 8
foo[5] = 0
foo[6] = 7
foo[7] = 8
foo[8] = 9
foo[9] = 10
foo[10] = 11
foo[11] = 12
My Question is: Why is happening here undefined behavior at foo[4]
? The array is defined proper with 12 elements.