Q: I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage.
A: Whenever a function returns a pointer, make sure that the pointed-to memory is properly allocated. For example, make sure you have not done something like
When a function returns, its automatic, local variables are discarded, so the returned pointer in this case is invalid (it points to an array that no longer exists).
#include <stdio.h>
char *itoa(int n) { char retbuf[20]; /* WRONG */ sprintf(retbuf, "%d", n); return retbuf; /* WRONG */ }
One fix would be to declare the return buffer as
static char retbuf[20];This fix is imperfect, since a function using static data is not reentrant. Furthermore, successive calls to this version of itoa keep overwriting the same return buffer: the caller won't be able to call it several times and keep all the return values around simultaneously.
See also questions 7.5b, 12.21, and 20.1.
References:
ISO Sec. 6.1.2.4