2

If a declare an array of size 4 and initialize it.
Int arr[4]={1,2,3,4} Why there is no error while I do arr[4] =5 or for any other index . While the size of array is 4 . Why there is not error . And what is logic behind this ????

I know there is not error . But I could not understanding logic behind this .

Ahsan Ayaz
  • 23
  • 3
  • 1
    Note that in many, many cases, enabling warnings and runtime checks will point out that mistake. – spectras Feb 02 '23 at 04:50
  • You can enable bounds checks in most compilers. They're disabled by default because they're slow. Look up "address sanitizer". – HolyBlackCat Feb 02 '23 at 05:01
  • 1
    C++ is a language that tries to compile to highly efficient code, therefor it will not generate checks for every little thing you do (Don't pay for what you don't use). This gives developers a lot of control, but also a lot of responsibilities. – Pepijn Kramer Feb 02 '23 at 05:02

1 Answers1

5

As opposed to some other languages, C++ does not perform any runtime bounds checking as you have observed. The size of the array is not actually stored anywhere and not available at runtime. As such, at runtime no such checks can be performed. This was a conscious choice by the language creators to make the language as fast as possible while still being able to opt into bounds checking with the solutions I have outlined below.

Instead, what happens is known as undefined behaviour which C++ has a lot of. This must be always avoided as the outcome is not guaranteed and could be different every time you run the program. It might overwrite something else, it may crash, etc.

You have several solution paths here:

  1. Most commonly you will want to use std::array such that you can access its .size() and then check for it before accessing:

    if (i < arr.size())
        arr[i] = value;
    else // handle error
    
  2. If you want to handle the error down the line you can use std::array and its .at() method which will throw a std::out_of_range in case the index is out of bounds: https://en.cppreference.com/w/cpp/container/array/at

    Example: http://coliru.stacked-crooked.com/a/b90cbd04ce68fac4 (make sure you are using C++ 17 to run the code in the example).

  3. If you just need the bounds checking for debugging you can enable that option in your compiler, e.g., GCC STL bound checking (that also requires the use of std::array)

Post Self
  • 1,471
  • 2
  • 14
  • 34