Bad array indexing is considered deadly

Ali Çehreli via Digitalmars-d digitalmars-d at puremagic.com
Wed May 31 14:30:05 PDT 2017


On 05/31/2017 02:00 PM, Steven Schveighoffer wrote:
 > On 5/31/17 3:17 PM, Moritz Maxeiner wrote:

 >> It is not that accessing the array out of bounds *leading* to data
 >> corruption that is the issue here, but that in general you have to
 >> assume that the index *being* out of bounds is itself the *result* of
 >> *already occurred* data corruption;
 >
 > To be blunt, no this is completely wrong.

Blunter: Moritz is right. :)

 > Memory corruption *already having happened* can cause any
 > number of errors.

True.

 > The point of bounds checking is to prevent memory corruption in
 > the first place.

That's just one goal. It also maintains an invariant of arrays: The 
index value must be within bounds.

 > I could memory corrupt the length of the array also (assuming a
 > dynamic array), and bounds checking merrily does nothing to
 > stop further memory corruption.

That's true but the language provides no tool to check for that. The 
fact that program correctness is not achievable in general should not 
have any bearing on bounds checking.

 >> and if data corruption occurred for
 >> the index, you *cannot* assume that *only* the index has been affected.
 >> The runtime cannot simply assume the index being out of bounds is not
 >> the result of already occurred data corruption, because that is
 >> inherently unsafe, so it *must* terminate asap as the default.
 >
 > The runtime should not assume that crashing the whole program is
 > necessary when an integer is out of range. Preventing actual corruption,
 > yes that is good. But an Exception would have done the job just fine.

How could an Exception work in this case? Catch it and repeat the same 
bug over and over again? What would the program be achieving? (I assume 
the exception handler will not arbitrarily decrease index values.)

Ali



More information about the Digitalmars-d mailing list