The first piece of code is:
#include <stdio.h> char *getString() { char *str = "Will I be printed?"; return str; } int main() { printf("%s", getString()); }
And the second piece of code is:
#include <stdio.h> char *getString() { char str[] = "Will I be printed?"; return str; } int main() { printf("%s", getString()); }
In both of the above codes,char pointer is returned which points to a local variable which could get overwritten but still code-1 manages to run successfully while code-2 print Garbage values.
Let a little extend your example and see where stored our data:
What we got? At my 32-bit system:
As you can see, char* var="123" points in data segment (https://en.wikipedia.org/wiki/Data_segment), but char[] located at stack.
Every time, when you leave your function where you alloc any variables at stack, this variables get undefined, since data allocated at stack (pointers too) invalid outside function. But in getString1() actually returns pointer value to data segment which outside stack, so this function works correctly, but allocated pointer get undefined at function exit.