I have a few questions about functions returning char *:
Here I have two programs, the green how the program works without any problems:And the red, the wrong way to return char *:Code:char *func(void) { char *returnstr; returnstr = (char *) malloc(100); // put something into the string return(returnstr); } int main() { char *str; str = func(); printf("%s", str); // I think I need to free() the str, // but to free here something that was allocated // inside func() looks kind of weird, and alittle stupid // so I'm not sure what do with the allocated memory... return(0); }Can someone please explain to me what is the problem with the red code, and why do I have to work the way I did with in the green code?Code:char *func(void) { char returnstr[100]={0}; // put something into the string return(returnstr); } int main() { printf("%s", func()); return(0); }
Thank you.



LinkBack URL
About LinkBacks



And that was my bad with reassigning the a pointer, however sand_man's code is correct because the data is cpy'd to the allocated memory which is fine to free(). I had re-assigned it to point to "abc" which is illegal to free, pretty bad example in the first place.