Array bounds checking

Ideally, by being careful and not doing that in the first place. There are lots of tools that add checking at runtime, but they are generally compiler/OS dependent.

Commented Jan 31, 2021 at 6:47 xar[i-1]=i*i; : when i is 0 , you access an element out of bounds. Commented Jan 31, 2021 at 9:02 i <= : array indices go from 0..n-1 so you access the last element in the loop out of bounds. Commented Jan 31, 2021 at 9:04

1 Answer 1

C as a language does not provide any provisions for bounds-checking beyond "keep track of it yourself". So there is not really a better solution in general other than being careful. There do exist programs like ASAN which can help detect such bugs at runtime though.

answered Jan 31, 2021 at 6:47 632 3 3 silver badges 11 11 bronze badges

+1 for ASan, but GCC will also catch OP's particular bad example code at compile time (with -Wall -Werror options, which of course should always be enabled during development of any new code). See: godbolt.org/z/9vWePx

Commented Jan 31, 2021 at 6:51

@JohnZwinck good point! Now if only it could help out in the case of something dynamically allocated :(