strange bug with unions?

Ali Çehreli via Digitalmars-d digitalmars-d at puremagic.com
Fri May 29 01:28:04 PDT 2015


On 05/29/2015 12:55 AM, seen wrote:
> I don't know why but when using a template union with a static ubyte
> array i get bizarre results!
>
> module main;
>
> import std.stdio;
> private union ByteConverter(T)
> {
>      ubyte[T.sizeof] bytes;

That's a fixed-length array (aka static array), which has value semantics.

>      T value;
> }
>
> ubyte[] toBytes(T)(T from) if (!is(T == const))

That function returns a slice to a...

> {
>      ByteConverter!T converter;
>      converter.value = from;
>      return converter.bytes;

... local static array. :(

Replace the return type with

a) auto

b) ubyte[T.sizeof]

> }
>
> T fromBytes(T)(in ubyte[] bytes)
> {
>      ByteConverter!T converter;
>      converter.bytes = bytes;
>      return converter.value;
> }
>
> void main(string[] args)
> {
>      writeln(fromBytes!uint(toBytes(34u)));// should print 32 but prints
> 1244564
> }
>
> why dose it print 1244564 the array is static size so why is it acting
> like bytes is a pointer not a static array?

Now it prints 34. :)

Ali



More information about the Digitalmars-d mailing list