What is going on in this code?

ag0aep6g via Digitalmars-d digitalmars-d at puremagic.com
Thu Apr 14 03:29:43 PDT 2016


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;
}
----


More information about the Digitalmars-d mailing list