Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array index out of bound behavior

Tags:

c++

arrays

c

Why does C/C++ differentiates in case of array index out of bound

#include <stdio.h> int main() {     int a[10];     a[3]=4;     a[11]=3;//does not give segmentation fault     a[25]=4;//does not give segmentation fault     a[20000]=3; //gives segmentation fault     return 0; } 

I understand that it's trying to access memory allocated to process or 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 compiler or linker give an error, aren't they aware of the array size? If not then how does sizeof(a) work correctly?

like image 834
Kazoom Avatar asked Mar 22 '09 22:03

Kazoom


1 Answers

The problem is that C/C++ doesn't actually do any boundary checking with regards to arrays. It depends on the OS to ensure that you are accessing valid memory.

In this particular case, you are declaring a stack based array. Depending upon the particular implementation, accessing outside the bounds of the array will simply access another part of the already allocated stack space (most OS's and threads reserve a certain portion of memory for stack). As long as you just happen to be playing around in the pre-allocated stack space, everything will not crash (note i did not say work).

What's happening on the last line is that you have now accessed beyond the part of memory that is allocated for the stack. As a result you are indexing into a part of memory that is not allocated to your process or is allocated in a read only fashion. The OS sees this and sends a seg fault to the process.

This is one of the reasons that C/C++ is so dangerous when it comes to boundary checking.

like image 183
JaredPar Avatar answered Oct 07 '22 20:10

JaredPar