Alex Rivera | Logout

Array index out of bound behavior

Asked 2009-03-22T22:27:15.010
52

Why does C/C++ differentiate in case of an array index out of bound?

#include <stdio.h>

int main()
{
    int a[10];
    a[3] = 4;
    a[11] = 3; // Does not give a segmentation fault
    a[25] = 4; // Does not give a segmentation fault
    a[20000] = 3; // Gives a segmentation fault
    return 0;
}

I understand that it's trying to access memory allocated to a process or a thread in case of a[11] or a[25] and it's going out of stack bounds in case of a[20000].

Why doesn't the compiler or linker give an error? Aren't they aware of the array size? If not, then how does sizeof(a) work correctly?

Edit
Report

1 Answer

2

As litb mentioned, some compilers can detect some out-of-bounds array accesses at compile time. But bounds checking at compile time won't catch everything:

int a[10];
int i = some_complicated_function();
printf("%d\n", a[i]);

To detect this, runtime checks would have to be used, and they're avoided in C because of their performance impact. Even with knowledge of a's array size at compile time, i.e. sizeof(a), it can't protect against that without inserting a runtime check.

answered 2009-03-23T02:38:11.243

Your Answer