Home > Enterprise >  Why there is no error when we assign value to an array outside of it's size
Why there is no error when we assign value to an array outside of it's size

Time:02-02

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 .

CodePudding user response:

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)

CodePudding user response:

In C and C , set an array index to a value greater than its size. This means that the behavior is not specified by the language standard, and results may vary across different compilers and systems. On some systems this may cause a segmentation fault, while on others it may have unexpected results or appear to have no effect at all.

The reason for this undefined behavior is that arrays are stored in blocks of memory, and when you access an index that exceeds the size of the array, you are accessing memory that is not in the array, and may contain other important data.

Therefore, it is best to always access array indices to avoid unknown behavior and ensure program reliability.

  •  Tags:  
  • c
  • Related