Array index out of bound in C

后端 未结 10 1127
抹茶落季
抹茶落季 2020-11-21 21:58

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

#include 
int main()
{
    int a[10];
    a[3]=4;
    a[11]=3;//doe         


        
10条回答
  •  不思量自难忘°
    2020-11-21 22:50

    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.

提交回复
热议问题