C++ Stickies : snprintf() [Safe Version of sprintf() that doesn’t suffer from buffer overruns]
int snprintf(char *str, size_t size, const char *format, ...);
int vsnprintf(char *str, size_t size, const char *format, va_list args);
-
Writes output to the string
str, under control of the format stringformat, that specifies how subsequent arguments are converted for output. It is similar to sprintf(3), except thatsizespecifies the maximum number of characters to produce. The trailingnulcharacter is counted towards this limit, so you must allocate at leastsizecharacters forstr.If
sizeis zero, nothing is written andstrmay benull. Otherwise, output characters beyond then-1st are discarded rather than being written tostr, and anulcharacter is written at the end of the characters actually written tostr. If copying takes place between objects that overlap, the behaviour is undefined.
Example,
#include <slack/std.h> #ifndef HAVE_SNPRINTF #include <slack/snprintf.h> #endif int main(int ac, char **av) { char buf[16]; char *str = buf; char *extra = NULL; int len; if (!av[1]) return EXIT_FAILURE; if ((len = snprintf(buf, 16, "%s", av[1])) >= 16) if (extra = malloc((len + 1) * sizeof(char))) snprintf(str = extra, len + 1, "%s", av[1]); printf("%s\n", str); if (extra) free(extra); return EXIT_SUCCESS; }