From https://stackoverflow.com/a/13067917/156458
snprintf ... Writes the results to a character string buffer. (...) will be terminated with a null character, unless buf_size is zero.
So why does the following example from The Linux Programming Interface explicitly set the last character of a string (assigned by snprintf()) to be \0?
char *
inetAddressStr(const struct sockaddr *addr, socklen_t addrlen,
char *addrStr, int addrStrLen)
{
char host[NI_MAXHOST], service[NI_MAXSERV];
if (getnameinfo(addr, addrlen, host, NI_MAXHOST,
service, NI_MAXSERV, NI_NUMERICSERV) == 0)
snprintf(addrStr, addrStrLen, "(%s, %s)", host, service);
else
snprintf(addrStr, addrStrLen, "(?UNKNOWN?)");
addrStr[addrStrLen - 1] = '\0'; /* Ensure result is null-terminated */
return addrStr;
}
Setting the last character of the target array to '\0' explicitly seems useless if snprintf conforms to the C Standard.
Note however that the Linux kernel uses its own version of the C library which may or may not conform to the C Standard. Most functions are older than the C99 standard where snprintf was first specified, which may explain implementation differences. The current version of the kernel's snprintf implementation does set the null terminator. The posted code seems to come from user code, not kernel code, so this is irrelevant.
Note also that some C libraries have non standard behavior. For example, Microsoft C runtime library did not support C99 extensions for almost 15 years after its publication and are still not fully conformant for various reasons. For example, snprintf has non-standard behavior for the %n conversion.
Note also that some Microsoft extensions with very similar names to the standard functions behave in surprising and confusing ways. For example _snprintf() will not set a null terminator in the target array if the output is truncated. see this documentation page for the gory details.
For the posted code, the C library is very unlikely to come from Microsoft, but the linux kernel may be used in systems with various C libraries: the GNU libc is used for most desktop distributions, but Android for example uses a different library. The author of the code fragment either:
snprintf writes the null terminator.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With