On Thursday, 14 April 2016 at 10:29:43 UTC, 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;
}
----

Thanks, that works perfectly! I couldn't figure it out and I knew I had to be missing something really basic. I still don't understand though why it works in release but not in debug.

Reply via email to