I was writing some C code today and I noticed something strange. First, I defined an array with a certain size. Then, I indexed it in a for loop and accidentally indexed it past the size that was allocated for it. I believe that this should have thrown an error, but I didn't get a compiler error or an error when I ran the executable.
The code went something like this:
#include <stdio.h>
#include "functions.h"
int main()
{
unsigned char arr1[5] = {1, 2, 3, 4, 5};
int N=100;
int arr2[N];
int i;
for(i=0;i<N;++i)
{
arr2[i] = i;
//Some function defined in a file functions.c
func1(arr2[i],arr1[i]);
}
return 1;
}
How does this not throw an error when I try to index, say, arr1[5]
?
Not that it is important to the question, but I realized that I needed to do a nested for loop. Like this:
#include <stdio.h>
#include "functions.h"
int main()
{
unsigned char arr1[5] = {1, 2, 3, 4, 5};
int N=100;
int arr2[N];
int i;
int j;
for(j=0;j<5;++i)
{
for(i=0;i<N;++i)
{
arr2[i] = i;
//Some function defined in a file functions.c
func1(arr2[i],arr1[j]);
}
}
return 1;
}