0

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;
}
Anthony K.
  • 11
  • 4
  • 3
    C doesn't enforce array bounds. It's the programmer's responsibility to access memory correctly. – sj95126 Dec 03 '22 at 01:58
  • Related: [How dangerous is it to access an array out of bounds?](https://stackoverflow.com/q/15646973/12149471) – Andreas Wenzel Dec 03 '22 at 02:00
  • 1
    This is an example of undefined behavior. See [Undefined, unspecified, and implementation-defind behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) – aschepler Dec 03 '22 at 02:00

0 Answers0