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;
}