Bad array indexing is considered deadly

Moritz Maxeiner via Digitalmars-d digitalmars-d at puremagic.com
Wed May 31 15:56:15 PDT 2017


On Wednesday, 31 May 2017 at 22:42:30 UTC, Jonathan M Davis wrote:
>
> I don't think that you even need to worry about whether memory 
> corruption occurred prior to indexing the array with an invalid 
> index. The fact that the array was indexed with an invalid 
> index is a bug. What caused the bug depends entirely on the 
> code. Whether it's a memory corruption or something else is 
> irrelevant. The contract of indexing arrays is that only valid 
> indices be passed. [...]

That is correct (and that was even mentioned in the OP), but from 
my PoV the argument was about whether that contract is sensible 
the way it is, so I was arguing for why I think the contract is 
good as it is.
*The contract says so* is not an argument supporting the case of 
*why* the contract is the way it is.


>
> We _could_ make it so that the contract of indexing arrays is 
> such that you're allowed to pass invalid values, but then [...]

Another reason as to why I support the current contract.

>
> As such, it really doesn't make sense to force all programs to 
> deal with arrays throwing Exceptions due to bad indices. If a 
> program can't guarantee that it's going to be passing a valid 
> index to an array, then it needs to validate the index first.
> And if that needs to be done frequently, it makes a lot of 
> sense to either create a wrapper function for indexing arrays 
> which does the check or to outright wrap arrays such that 
> opIndex on that type does the check and throws an Exception 
> before the invalid index is passed to the array. And if the 
> wrapper function is @trusted, it _should_ make it so that 
> druntime doesn't check the index, avoiding having redundant 
> checks.

Precisely, and that is why I stated that I think he should use a 
wrapper.

>
> I can understand Steven's frustration, but I really think that 
> we're better off the way it is now, even if it's not ideal for 
> his current use case.

I agree.




More information about the Digitalmars-d mailing list