I came across an example in a page outlining the various ways to represent a string in C structures. It explains that an array defined in a function outside main will be stored in the stack segment and as such will not necessarily be present following its return potentially causing a runtime error.
HIGHLIGHTED POSSIBLE DUPLICATE EXPLAINED WHY THE ARRAY FAILED ON RETURN I.E THE POINTER TO ELEMENT 0 RETURNED IS NO LONGER VALID BUT DID NOT SHOW THAT THE REASON VARIABLES OF THE SAME STORAGE CLASS (AUTO) ARE SUCCESSFUL IS THAT THEY PASS A VALUE WHICH SURVIVES THE REMOVAL OF THE STACK FRAME
" the below program may print some garbage data as string is stored in stack frame of function getString() and data may not be there after getString() returns. "
char *getString()
{
char str[] = "GfG"; /* Stored in stack segment */
/* Problem: string may not be present after getSting() returns */
return str;
}
int main()
{
printf("%s", getString());
getchar();
return 0;
}
I understand that other local C variables will also be defined in their respective stack frames and obviously they can be returned so why is it an issue for arrays?
Thanks