Bug 71813 - fprintf/printf function exception
Summary: fprintf/printf function exception
Status: RESOLVED INVALID
Alias: None
Product: gcc
Classification: Unclassified
Component: c (show other bugs)
Version: 4.9.3
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2016-07-08 05:56 UTC by Bing
Modified: 2016-07-10 15:44 UTC (History)
1 user (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Bing 2016-07-08 05:56:04 UTC
I wrote a program:
#include <string.h>
#include <stdio.h>

char *test2()
{
	char testArray[2];
	char *testP;

	memcpy(testArray, "2", 2);

	testP = testArray;

	return testP;
}

char *test()
{
	return test2();
}

int main()
{
	char *ret;

	ret = test();

	fprintf(stdout, "%s\n", ret);

	return 0;
}

but, when I ran it, it output some things that people cannot understand.
such as:'�d/
when I changed fprintf to printf, it output NULL.
then, I use gdb-7.10.1 to check it, 
I could know:
before fprintf/printf, the value of ret is correct.
but after fprintf/printf, it went wrong.
Comment 1 Andrew Pinski 2016-07-08 06:10:50 UTC
testArray goes out of scope and you access it outside of the scope.  Undefined behavior.
Comment 2 Manuel López-Ibáñez 2016-07-10 15:44:25 UTC
(In reply to Andrew Pinski from comment #1)
> testArray goes out of scope and you access it outside of the scope. 
> Undefined behavior.

GCC 6.1 even warns you about this with -Wall -Wextra -O2:

warning: function returns address of local variable [-Wreturn-local-addr]

See https://gcc.gnu.org/wiki/FAQ#misoptimization