I wrote a program:
memcpy(testArray, "2", 2);
testP = testArray;
ret = test();
fprintf(stdout, "%s\n", ret);
but, when I ran it, it output some things that people cannot understand.
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.
testArray goes out of scope and you access it outside of the scope. Undefined behavior.
(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]