What's the bug in the following code:

```d
import std.digest.md;
import std.stdio;

pragma(inline, false) // just in case
string getHash()
{
    ubyte[16] hash = [1,2,3,4,5,6,6,78,8,8,7,7,6,3,2,3];
    string a = toHexString(hash);
    return a;
}

pragma(inline, false) // just in case
void destroystack()
{
    writeln("asd","asd","asd","asd","asd","asd");
}

void main()
{
    string a = getHash();
    destroystack();
    writeln(a);
}
```

Hint: when changing
```
    string a = toHexString(hash);
    return a;
```
to
```
    return toHexString(hash);
```
the compiler errors with:
`Error: escaping reference to stack allocated value returned by toHexString(hash)`.

So:
- the documentation of toHexString says that the overloads returning a string return a GC allocated string - the _implementation_ of `string toHexString(...)` does a `new char[16]`, so GC allocates. - `string a = toHexString(hash);` calls `char[num*2] toHexString(...)` instead of `string toHexString(...)`. OOPS.

https://issues.dlang.org/show_bug.cgi?id=16519

I don't know whether this is a compiler bug (choosing the wrong overload) or a Phobos bug (overloads don't work like that). How are template overloads involving `string` and `char[constant]` return values supposed to work?

Still can't believe I am the first one to run into this, what am I doing wrong?

-Johan

Reply via email to