Monday, August 07, 2006

return array, pointer ...

This one is in interivew: bi

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.

There are two better solution:
1. have the caller pass space for the result:
char *itoa(int n, char *retbuf)
{
sprintf(retbuf, "%d", n);
return retbuf;
}
...
char str[20];
itoa(123, str);

2. Use malloc or new:

char *itoa(int n)
{
char *retbuf = new char [20];
if(retbuf != NULL)
sprintf(retbuf, "%d", n);
return retbuf;
}
...
char *str = itoa(123);
delete []str;

No comments:

Post a Comment