|
From: Ivo R. <iv...@iv...> - 2015-01-02 04:39:23
|
2015-01-02 2:21 GMT+01:00 John Reiser <jr...@bi...>: > > If there is any doubt [you have at least 1% doubt] then you should replace > all uses > of sprintf with snprintf instead. Using snprintf is not a fool-proof > cure-all. > If the length limit is reached then the result has no terminating '\0', > so subsequent reads (such as via %s) might over-read the space for the > result. > > While I strongly agree with everything that John R. has written, snprintf() actually *does* terminate the output buffer with terminating '\0'. See the POSIX specification [1] for snprintf(): "The *snprintf*() function shall be equivalent to *sprintf*(), with the addition of the *n* argument which states the size of the buffer referred to by *s*. If *n* is zero, nothing shall be written and *s* may be a null pointer. Otherwise, output bytes beyond the *n*-1st shall be discarded instead of being written to the array, and a null byte is written at the end of the bytes actually written into the array." and a discussion [2] about snprintf() on Windows. I. [1] http://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html [2] http://stackoverflow.com/questions/7706936/is-snprintf-always-null-terminating |