Here is the code changed a bit from this thread:How to return a string in my C code?
#include <stdio.h>
const char * getString();
int main()
{
printf("hello world\n");
printf("%s\n", getString());
printf("%s\n", getString2());
return 0;
}
const char * getString()
{
const char *x = "abcstring";
return x;
}
const char * getString2()
{
return "abcstring";
}
This looks a bit confusing to me because the memory space which x
points to, "abcstring"
, in getString
seems to be on stack instead of on heap. Therefore, the allocated memory for x
may be freed at the end of getString
. If so, will printf("%s\n", getString());
fail?
And What about printf("%s\n", getString2());
?