Bug 890 – Returning char[4] and assigning to char[] produces unexpected results.

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D1 (retired)
Platform
All
OS
Linux
Creation time
2007-01-26T03:45:00Z
Last change time
2014-02-16T15:22:12Z
Assigned to
bugzilla
Creator
d

Comments

Comment #0 by d — 2007-01-26T03:45:46Z
import std.stdio; char[] get_str() { char[4] retVal = ['t', 'e', 's', 't']; return retVal; } void main() { char[] res = get_str(); writefln(res == "test" ? "SUCCESS" : "FAIL"); } Results: GDC 0.21 Mac, gdc -o testcase_debug -fdebug -fbounds-check unique.d FAIL GDC 0.21 Mac, gdc -o testcase -O3 -finline -fno-bounds-check unique.d SUCCESS DMD 1.002 Linux, dmd -oftestcase_debug -debug unique.d FAIL DMD 1.002 Linux, dmd -oftestcase -O -release -inline unique.d SUCCESS ------ Attempting to output res results in "`_Error: 4invalid UTF-8 sequence" when this comparison fails. This bug also has a weird bonus: If the comparison is moved into a function it succeeds in debug builds, but attempting to output res results in the above UTF-8 error.
Comment #1 by bugzilla — 2007-01-26T03:49:28Z
It fails because statically dimensioned arrays, like char[4], are allocated on the stack, and the return statement is returning a reference to that stack variable. When the function returns, the stack variable becomes garbage.
Comment #2 by benoit — 2007-01-26T04:27:26Z
Please add an error for this. Probably it is not possible to catch all such cases. But it should be possible for the trivial case: returning a reference to local defined char[4]. This will prevent more ppl from having that problem. I changed this item from bug to enhancement.
Comment #3 by bugzilla — 2007-02-12T03:41:44Z
Fixed DMD 1.005