3 ms·
Mostly good advice, but the multiple `snprintf` example is wrong - it contains a buffer overflow. snprintf returns the number of characters that would be writte
by nneonneo 8y ago
Mostly good advice, but the multiple `snprintf` example is wrong - it contains a buffer overflow. snprintf returns the number of characters that would be written, so when you do
i += snprintf(i, e-i, "%s", b1);
i would end up past e if b1 is overlong. Then in the next line
i += snprintf(i, e-i, "%s", b2);
e-i is negative, but snprintf takes a size_t so this will overflow badly.
The best solution, AFAICT, is the following:
int res;
res = snprintf(i, e-i, "%s%s%s", b1, b2, b3);
if(res >= e-i) {
/* handle overflow */
return -1;
} else {
i += res;
}
/* subsequent snprintf's here */