Say I have function that returns a pointer to a character, or more specifically a string:
char* fun_that_returns_string () {
char* teststr = "Hello World";
return teststr;
}
and now I call that function and assign it's return value to a char*
somewhere else:
char* s = fun_that_returns_string();
I can then print the returned string and get the "correct" result:
printf("%s\n", s);
Output:
> Hello World
Shouldn't the local value teststr
or its address be invalid outside of the function, since it is cleared after returning? Is it undefined behaviour and I was just lucky that is was not overwritten before I printed? If that is the case, what is the correct way to handle returned strings?
Another example: When I use predefined functions like e.g. ctime(3)
from time.h
which returns a char*
and I call the function directly in the arguments of another function
time_t t;
t = time(&t);
foo(ctime(&t));
This function will receive the return value of ctime()
, which is a pointer to the first character of the time string, as a copy. So it's kind of the same as above? My understanding is that whatever happened inside ctime()
should not be dereferenced any more, unless it was malloc'ed on the heap (but in that case I would have to free it myself)?
My professor used this ctime()-direct-argument-thing in some example code and I just can't wrap my head around it.