Lets say I am iterating over an array, but go beyond this array because my loop is stupid.
If an object in memory is located directly after this array of the same type as this array, can
checking array[invalid_index] == nullptr
protect me?
What is the correct way to check whether an index (size is not known) is valid for a C array?
It's not possible to determine the size of an array through a pointer to it's first element. You need to communicate the size somehow.
Common strategies are to keep your array as an array and communicate the size through the type system, provide the size as a separate value or use a sentinel value (like a null character in a c string). In c++, it's recommended to use std::vector
or std::array
which always know their own size.
Trying to dereference an array element beyond the bounds of that array is undefined behavior. As soon as you try to read array[invalid_index]
you have undefined behavior. So it's not possible to use array[invalid_index]
for any useful purpose, including bounds checking. nullptr
has no effect here at all.