space allocation for sprintf()

Lars Wirzenius wirzeniu at klaava.Helsinki.FI
Mon Jun 10 01:51:47 AEST 1991


In article <1167 at mwtech.UUCP> martin at mwtech.UUCP (Martin Weitzel)
writes:
>[ as a suggestion for handling problems when sprintf overflows 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();

May I further suggest that another character than '\0' be used.  A
frequent problem (for me, at least) is the 'off-by-one error' (e.g.,
some limit or array bound is one too small). This type of error would
print one character too many to the buffer, but this isn't noticed if
the validation character is '\0'. If available, a char value that
doesn't correspond to a normal character would be best.
-- 
Lars Wirzenius     wirzeniu at cc.helsinki.fi



More information about the Comp.lang.c mailing list