Bad array indexing is considered deadly

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Wed May 31 14:00:43 PDT 2017


On 5/31/17 3:17 PM, Moritz Maxeiner wrote:
> On Wednesday, 31 May 2017 at 13:04:52 UTC, Steven Schveighoffer wrote:
>> [...]
>>
>> What are your thoughts? Have you run into this? If so, how did you
>> solve it?
>>
>
> 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. Memory corruption *already 
having happened* can cause any number of errors. The point of bounds 
checking is to prevent memory corruption in the first place. 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.

> 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.

But that ship, as I said elsewhere, has sailed. We can't change it to 
Exception now, as that would break just about all nothrow code in existence.

> So in your specific use case I would say use a wrapper. This is one of
> the reasons why I am working on my own library for data structures (libds).

That is my conclusion too. Is your library in a usable state? Perhaps we 
should not repeat efforts, though I wasn't planning on making a robust 
public library for it :)

-Steve


More information about the Digitalmars-d mailing list