Thread overview
Classical bug
Jan 27, 2015
Fyodor Ustinov
Jan 27, 2015
Vladimir Panteleev
Jan 27, 2015
Fyodor Ustinov
Jan 27, 2015
Vladimir Panteleev
Jan 27, 2015
bearophile
Jan 27, 2015
Fyodor Ustinov
January 27, 2015
Hi!

I thought at least in safe mode this code will not compile or I get warning:

byte[] func() @safe {
 byte[1024] buffer;
 return buffer[0..3];
}

void main() {
  auto b = func();
  b[0] = 1;
}

But no any error. Dlang do not catch this?

WBR,
    Fyodor.
January 27, 2015
On Tuesday, 27 January 2015 at 11:41:21 UTC, Fyodor Ustinov wrote:
> byte[] func() @safe {
>  byte[1024] buffer;
>  return buffer[0..3];
> }
>
> void main() {
>   auto b = func();
>   b[0] = 1;
> }

In 2.067, this is an error:

test.d(4,9): Error: escaping reference to local variable buffer
January 27, 2015
On Tuesday, 27 January 2015 at 11:51:43 UTC, Vladimir Panteleev wrote:
> In 2.067, this is an error:
>
> test.d(4,9): Error: escaping reference to local variable buffer

Always or only in safe mode?
January 27, 2015
On Tuesday, 27 January 2015 at 12:01:11 UTC, Fyodor Ustinov wrote:
> On Tuesday, 27 January 2015 at 11:51:43 UTC, Vladimir Panteleev wrote:
>> In 2.067, this is an error:
>>
>> test.d(4,9): Error: escaping reference to local variable buffer
>
> Always or only in safe mode?

Always. But the check seems very simple, and is easily circumvented. This compiles:

byte[] func() {
 byte[1024] buffer;
 auto p = buffer[0..3];
 return p;
}
January 27, 2015
Vladimir Panteleev:

> But the check seems very simple, and is easily circumvented. This compiles:
>
> byte[] func() {
>  byte[1024] buffer;
>  auto p = buffer[0..3];
>  return p;
> }

I guess such bugs will be detected (in safe code only!) after the implementation of: http://wiki.dlang.org/DIP69 Currently we are implementing a kind of pre-phase: http://wiki.dlang.org/DIP25

And here I have asked for @safe to become the default (Walter seems not against this idea):
https://d.puremagic.com/issues/show_bug.cgi?id=13838

Bye,
bearophile
January 27, 2015
On Tuesday, 27 January 2015 at 12:02:59 UTC, Vladimir Panteleev wrote:

> Always. But the check seems very simple, and is easily circumvented. This compiles:
>
> byte[] func() {
>  byte[1024] buffer;
>  auto p = buffer[0..3];
>  return p;
> }

I think this is the first step of a long and difficult way.

byte[] func(byte[] a) {
 return a[0..1];
}

byte[] func1() {
 byte[1024] buffer;
 return func(buffer[1...$]);
}

byte[] func2() {
 static byte[1024] buffer;
 return func(buffer[1..$]);
}