[Issue 16519] New: toHexString always returns stack allocated string

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Wed Sep 21 05:04:13 PDT 2016


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

          Issue ID: 16519
           Summary: toHexString always returns stack allocated string
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: major
          Priority: P1
         Component: phobos
          Assignee: nobody at puremagic.com
          Reporter: jbc.engelen at gmail.com

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);
}
```
It prints garbage after the "asdasdasdasdasdasd" line.

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.

I don't know whether this is a compiler bug (choosing the wrong overload) or a
Phobos bug (overloads don't work like that).

--


More information about the Digitalmars-d-bugs mailing list