Big problem!
return str;
str
is a local variable. You must not pass its address to the caller because the contents of what it's pointing to are not guaranteed to be what you assigned to it in example
. This wouldn't be a problem if you defined str
to be static
:
static char str[12];
Edit 1
You can also malloc
memory for str
:
char *str = malloc(12);
If you choose this method, you must remember to free
the dynamically allocated memory to prevent a memory leak.
Another method is to make str
global:
char str[12];
char *example(void)
{
...
}
It is generally best to keep the scope of variables as limited as possible, however.
Edit 2
Still another method is to have the caller allocate memory for the string. The following is an example:
void example(char *str, size_t length)
{
strncpy(str, "hello world", length);
str[length - 1] = '\0'; // Guarantee string '\0' terminated
}
int main(void)
{
char str[12];
example(str, sizeof(str));
printf("%s\n", str);
exit(EXIT_SUCCESS);
}
The problem with this method is that, generally, the caller does not know the length of the string to be returned.