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

D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 890 - Returning char[4] and assigning to char[] produces unexpected results.
Summary: Returning char[4] and assigning to char[] produces unexpected results.
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D1 (retired)
Hardware: All Linux
: P2 enhancement
Assignee: Walter Bright
URL:
Keywords:
Depends on:
Blocks:
Reported: 2007年01月26日 03:45 UTC by Jeff McGlynn
Modified: 2014年02月16日 15:22 UTC (History)
0 users

See Also:


Attachments
Add an attachment (proposed patch, testcase, etc.)

Note You need to log in before you can comment on or make changes to this issue.
Description Jeff McGlynn 2007年01月26日 03:45:46 UTC
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 Walter Bright 2007年01月26日 03:49:28 UTC
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 Frank Benoit 2007年01月26日 04:27:26 UTC
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 Walter Bright 2007年02月12日 03:41:44 UTC
Fixed DMD 1.005


AltStyle によって変換されたページ (->オリジナル) /