Code:
char* foo()
{
char a[] = "abc";
return a;
}
char* bar()
{
char* a = malloc(4);
a = "abc";
free(a); // Needs this.
return a;
}
char* fine()
{
return "abc";
}
int main()
{
char* s;
printf("%s\n", foo()); // Err: Stack data goes out of scope
printf("%s\n", bar()); // Err: Heap data needs free'ing, no no
printf("%s\n", fine()); // Okay: In data section. Fine.
return 0;
}
If you need data, it's going to have to come from a safe place. What you could be doing, is passing a local pointer of main to a function (with preallocated memory on heap or stack) and then strcpy (not assign the pointer!) whatever stuff you generate in foo() or bar(), and then continue. Like this:
Code:
char* foobar(char* s)
{
char a[] = "abc";
strcpy(s, a); // Not assigning s to a, strcpy'ing!
return s;
}
int main()
{
char* s = malloc(64); // Needs allocation!
printf("%s", foobar(s));
return 0;
}