string is a pointing to a local char array (on the stack), not to a dynamically allocated chunk of memory (on the heap). Things on the stack go bye-bye once they go out of scope (i.e. when the function ends). Things on the heap stay until you free that memory.
Pass the result string as a parameter, so the responsibility for allocating it is with the caller. Eg. strcpy()
Make the array static, so the function reserves a fixed sized array. Eg. asctime().
The disadvantage of this is calling the same function twice trashes the previous result.
Allocate the string inside the function and return the newly allocated memory. The non-standard strdup() would be an example.
The disadvantage is that the caller has to know it was allocated, and then free it at some point.
--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.