[Issue 927] New: writefln() is duplicating values for parameters supplied

Derek Parnell derek at psych.ward
Sat Feb 3 15:32:02 PST 2007


On Sat, 3 Feb 2007 18:43:15 +0000 (UTC), d-bugmail at puremagic.com wrote:


> char[]
> FourCharCodeAsString(FourCharCode inVal)
> {
>         char[4] s;
> 
>         s[0] = (inVal >> 24 & 0xFF);
>         s[1] = (inVal >> 16 & 0xFF);
>         s[2] = (inVal >> 8 & 0xFF);
>         s[3] = (inVal >> 0 & 0xFF);
> 
>         return s;
> }

As Walter pointed out, the return is referencing a local stack variable.

However, another way of resolving this could be ...

char[]
FourCharCodeAsString(FourCharCode inVal)
{
        char[] s;

        s ~= (inVal >> 24 & 0xFF);
        s ~= (inVal >> 16 & 0xFF);
        s ~= (inVal >> 8 & 0xFF);
        s ~= (inVal >> 0 & 0xFF);

        return s;
}

In other words, seeing you are trying to return a char[], you might as well
create a char[] (and not char[4]) to return. The char[], being a
variable-length array is created as a heap item and so the return statement
returns its heap reference and not any stack data.

-- 
Derek Parnell


More information about the Digitalmars-d-bugs mailing list