The following C function:
int sprintf ( char * str, const char * format, ... );
writes formatted data to a string. The size of the array pa
Most people will tell you to use snprintf()
because it won't overrun the end of your buffer.
And this is OK advice. The usual "design pattern" is to declare a temporary fixed-size buffer that is larger than the string is ever likely to be and snprintf()
to that. If the string needs to be saved for a while you can then measure its length, malloc(3)
another, and strcpy(3)
the temporary buffer to the semi-permanent malloc()
buffer.
There is another way.
C99 specifies that if the buffer is NULL then no bytes are written but the actual length that would have been written is returned. This allows you to do a dummy first pass, malloc() a buffer, and then snprintf()
to that buffer. (In theory you could use plain sprintf()
, as the length is now known, but I wouldn't.)
Anyway, I'm not sure I would count on all this if my program had to run on every OS ever made in the past, but it's a reasonable pattern for most people to use these days.