D defined behavior

ag0aep6g anonymous at example.com
Mon Apr 27 19:04:08 UTC 2020


On Monday, 27 April 2020 at 14:07:49 UTC, Luís Marques wrote:
> I've lost track. Does D have undefined behavior at all? (e.g. 
> outside @safe code).

In @system and @trusted code, there is plenty undefined behavior. 
Just search the spec for it:

https://www.google.com/search?q=%22undefined%20behavior%22%20site:dlang.org/spec

Per definition, @safe is supposed to be free of undefined 
behavior [1]. But there are many holes in the system, so that's 
not really true at the moment. Maybe we get there some day. Even 
then, all guarantees are off when you feed bad data to @safe code 
from @system code (e.g. an invalid pointer).

> In any case, I imagine that the D spec (ha!) would dictate that 
> the following code should print 0x10001, although that's not 
> quite clear.
>
> GDC (optimized) prints 0x1.
> LDC2 prints 0x10001, but I suspect only because LLVM doesn't 
> happen to do the same optimization, not because this is handled 
> properly.
>
> ```
> import std.stdio;
>
> @safe:
>
> int foo(int* a, int* b) {
>     *a = 1;
>     *b = 1;
>     return *a;
> }
>
> void main() {
>     ubyte[6] buffer;
>     auto a = cast(int[]) (buffer[0 .. 4]);
>     auto b = cast(int[]) (buffer[2 .. 6]);
>     writefln("0x%X", foo(&a[0], &b[0]));
> }
> ```

As far as I'm aware, an implementation can only assume alignment 
on GC pointers [2]. It cannot assume that two `int*`s don't point 
to overlapping locations. So GDC shouldn't do that optimization.

Then again, Walter wants to disallow passing multiple mutable 
references to the same memory with DIP 1021 [3]. If he goes 
through with that, implementations should reject that code.


[1] https://dlang.org/spec/function.html#function-safety
[2] https://dlang.org/spec/attribute.html#align
[3] 
https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1021.md


More information about the Digitalmars-d mailing list