space allocation for sprintf()

Martin Weitzel martin at mwtech.UUCP
Fri Jun 7 20:11:15 AEST 1991


In article <1991Jun5.174543.266 at dg-rtp.dg.com> vook at narnia.rtp.dg.com (Eric R Vook) writes:
>"(It is the programmer's responsibility to ensure that the destination
>  string area is large enough to contain the output generated by the
>  formatting operation.)"
>
>    How do you know how much space to allocate?
>    How do you know when you didn't allocate enough?

In article <1991Jun6.162723.27307 at zoo.toronto.edu> henry at zoo.toronto.edu (Henry Spencer) answers:
>The fast answers are "you have to know how sprintf is being used and figure
>out the longest string your parameters can result in" and "basically, you
>don't".

This is also my standard answer and I generally avoid using sprintf
if I can't reliably calculate the required size of the buffer.

But since I know that there are some outthere who will continue to use
sprintf also when the buffer size couldn't be reliably determined, I have
a suggestion (which may also help to check your calculations if you
*think* you made the buffer large enough). If you are too lazy to follow
Chris Toreks complete solution to the problem, at least write your code
as follows:

********* NOTE THAT THIS DOESN'T GUARANTEE TO CATCH ALL PROBLEMS  *********
********* ON ANY MACHINE WHEN WRITING PAST THE END OF THE BUFFER! *********

	#define MAX 40		/* if you think that 40 is enough */
	char buffer[MAX+1];
	buffer[MAX] = '\0';
	sprintf(buffer, ......);
	if (buffer[MAX] != '\0') abort();
	
********* NOTE THAT THIS DOESN'T GUARANTEE TO CATCH ALL PROBLEMS  *********
********* ON ANY MACHINE WHEN WRITING PAST THE END OF THE BUFFER! *********

But in general it's better than nothing, as on many architectures you
will first overwrite other local variables and possibly the stack frame,
then parameters of the function which contains this code and then locals,
stack frames, and parameters of the calling functions. If your function
never returns nor uses any other locals you have a good chance to at least
detect the problem immediately.

********* NOTE THAT THIS DOESN'T GUARANTEE TO CATCH ALL PROBLEMS  *********
********* ON ANY MACHINE WHEN WRITING PAST THE END OF THE BUFFER! *********
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.lang.c mailing list