What is going on in this code?

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Apr 14 06:31:25 PDT 2016


On 4/14/16 6:29 AM, ag0aep6g wrote:
> On 14.04.2016 12:14, Carlin wrote:
>> import std.stdio;
>> import std.bitmanip;
>>
>> ubyte[] serialize(uint t)
>> {
>>      ubyte[] bytes = nativeToBigEndian(t);
>>      return bytes;
>> }
>>
>> void main()
>> {
>>      writeln(serialize(0));
>> }
>
> Your code is wrong. It's really easy to get wrong, though. Too easy
> probably.
>
> nativeToBigEndian returns a fixed-size array. That's a value type. By
> assigning it to a ubyte[], you're slicing the return value. That is, you
> make a reference to temporary data. The reference becomes invalid as
> soon the assignment is over, so you're returning a slice to garbage memory.
>
> To make a ubyte[] from the result of nativeToBigEndian, you have to dup it:
> ----
> ubyte[] serialize(uint t)
> {
>      return nativeToBigEndian(t).dup;
> }
> ----

That is awful.

I propose we make slicing such a return value implicitly an error. I 
can't think of a valid reason for allowing it.

I'm not the only one: https://issues.dlang.org/show_bug.cgi?id=12625

-Steve


More information about the Digitalmars-d mailing list