Interview Questions

I have a function that is supposed to return a string ...

C Interview Questions and Answers


(Continued from previous question...)

I have a function that is supposed to return a string ...

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
#include <stdio.h>

char *itoa(int n)
{
char retbuf[20]; /* WRONG */
sprintf(retbuf, "%d", n);
return retbuf; /* WRONG */
}

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).
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.

(Continued on next question...)

Other Interview Questions