Because the lifetime of the string has already ended by the time you print it.
Local variables, such as string2
in Func
, are often stored in the stack, which is a very dynamic structure that changes every time a function is called or returned. (The actual behavior of the program stack is a bit too complex to elaborate here, but keep in mind that stuff in the stack doesn't survive the function that puts it there.)
By the time the function returns, string2
is no longer necessary, and thus it might be overwritten with garbage data. Nevertheless, Func
returns a pointer to string2
(remember that the name of an array is a pointer to its contents) — thus returning a pointer to the stack-allocated string that is being overwritten with garbage data. Printing the data referenced by this pointer (in main
, via string1
) just prints that garbage.
There are two ways of solving this issue. One is to let the caller handle memory allocation, and pass the allocated area to the callee, like so:
#include <stdio.h>
#include <string.h>
void Func(char *);
int main (void) {
char string[10];
Func(string);
puts(string);
return 0;
}
void Func (char * string) {
strcpy(string, "test");
}
...and another way is to let the callee handle the allocation, but remembering that the caller must free it, like so:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * Func(void);
int main (void) {
char * string = Func();
puts(string);
free(string);
return 0;
}
char * Func (void) {
char * string = malloc(10);
strcpy(string, "test");
return string;
}
Either way would solve your issue, and which one you choose is a matter of design.