Question 7.5

I have a function that is supposed to return a string, but when it returns to its caller, the returned string is garbage.


Make sure that the pointed-to memory is properly allocated. The returned pointer should be to a statically-allocated buffer, or to a buffer passed in by the caller, or to memory obtained with malloc, but not to a local (automatic) array. In other words, never do something like


char *itoa(int n) { char retbuf[20]; /* WRONG */ sprintf(retbuf, "%d", n); return retbuf; /* WRONG */ }
One fix (which is imperfect, especially if the function in question is called recursively, or if several of its return values are needed simultaneously) would be to declare the return buffer as
		static char retbuf[20];

See also questions 12.21 and 20.1.

References: ANSI Sec. 3.1.2.4
ISO Sec. 6.1.2.4


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback