Contracts, Undefined Behavior, and Defensive,Programming

Timon Gehr timon.gehr at gmx.ch
Mon Jun 15 13:03:55 UTC 2020


On 15.06.20 14:45, Paul Backus wrote:
> On Monday, 15 June 2020 at 04:08:28 UTC, Dukc wrote:
>> On Saturday, 13 June 2020 at 08:52:18 UTC, Johannes Pfau wrote:
>>> [snip]
>>
>> A very good point, has not occured to me before. But I think I can 
>> give a more specific example of what you're trying to convey:
>>
>> ```
>> @safe auto readIndex(int[] arr, size_t i)
>> in (i < arr.length)
>> {    return arr[i];
>> }
>> ```
>>
>> Because the compiler is free to assume that the contract holds, it can 
>> elide the array bounds check. If it does that, it results in memory 
>> violation from `@safe` code.
>>
>> This is something that should only be possible if `-boundscheck=off`. 
>> Not otherwise.
> 
> Well, the compiler has an option specifically for in contracts, 
> `-checkaction=in=[on|off]`, so probably what should be done is to give 
> that option a `safeonly` value like what `-boundscheck` has.

One may want to disable assertion checking without potentially causing 
UB in @safe code. In fact, I think this is more common.


More information about the Digitalmars-d mailing list