Array index out of bound in C

后端 未结 10 1136
抹茶落季
抹茶落季 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 23:03

    As JaredPar said, C/C++ doesn't always perform range checking. If your program accesses a memory location outside your allocated array, your program may crash, or it may not because it is accessing some other variable on the stack.

    To answer your question about sizeof operator in C: You can reliably use sizeof(array)/size(array[0]) to determine array size, but using it doesn't mean the compiler will perform any range checking.

    My research showed that C/C++ developers believe that you shouldn't pay for something you don't use, and they trust the programmers to know what they are doing. (see accepted answer to this: Accessing an array out of bounds gives no error, why?)

    If you can use C++ instead of C, maybe use vector? You can use vector[] when you need the performance (but no range checking) or, more preferably, use vector.at() (which has range checking at the cost of performance). Note that vector doesn't automatically increase capacity if it is full: to be safe, use push_back(), which automatically increases capacity if necessary.

    More information on vector: http://www.cplusplus.com/reference/vector/vector/

提交回复
热议问题