It's kind of hard to word my question so I'll just give a code example:
#include <stdio.h>
typedef struct {
char *str;
} strHold;
void f2(char *s)
{
*s = "Char 2";
}
void f3(strHold *str)
{
(*str).str = "Struct 2";
}
int main()
{
char *s1 = "Char 1";
strHold str1;
str1.str = "Struct 1";
//f2(s1);
f3(&str1);
printf("%s, ", s1);
printf("%s", str1.str);
return 0;
}
this C program runs, and even displays "Struct 2" on the second print. However function f2 doesn't work, as in, if I remove the comment, the program crashes. I'm actually not surprised that f2 doesn't work, I'm more wondering why does f3 work?
When I define a string constant inside a function's scope, that data should be freed once I exit the scope of the function, right? Which means that data would turn into garbage once I return into the calling function scope.
So... how comes the structure version works? Can somebody explain how memory works in both of those situations, and what's the "correct" way to initialize strings of an unknown length in a calling function from a function that it calls?