]> git.ipfire.org Git - thirdparty/collectd.git/commitdiff
common: Reserve a null byte when calling `strncpy`.
authorFlorian Forster <octo@collectd.org>
Thu, 11 Jan 2024 20:44:39 +0000 (21:44 +0100)
committerFlorian Forster <octo@collectd.org>
Mon, 15 Jan 2024 07:40:06 +0000 (08:40 +0100)
While `sstrncpy` guarantees a null terminated string, some compilers don't get
the memo and complain about the buffer size being equal to the size provided to
*strncpy(3)*. This *is* a potential source of error with *strncpy(3)*, because
if the source string is longer than the buffer, the buffer is not null
terminated. That is the precise reason `sstrncpy` exists in the first place.

Make these compilers happy by decreasing the size passed to *strncpy(3)* by
one.

src/utils/common/common.c

index ad72e93fffa3e98e7d85d687d79fc118d9a304a3..31e6146af798ce64d658594692a58c6c9df12f4f 100644 (file)
@@ -85,8 +85,10 @@ static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
 #endif
 
 char *sstrncpy(char *dest, const char *src, size_t n) {
-  strncpy(dest, src, n);
-  dest[n - 1] = '\0';
+  if (n > 0) {
+    strncpy(dest, src, n - 1);
+    dest[n - 1] = 0;
+  }
 
   return dest;
 } /* char *sstrncpy */