From c23a7e623209dae6fb36366c2e717690c9bfa042 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Mon, 5 Aug 2024 01:21:09 -0700 Subject: [PATCH] Prefer memcpy to strncpy if either will do strncpy is trickier and a bit slower. * src/function.c (func_realpath, func_abspath): * src/misc.c (xstrndup): Prefer memcpy or mempcpy to strncpy when the source length is known. --- src/function.c | 12 ++++++------ src/misc.c | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/function.c b/src/function.c index bf4f2abb..133e33a3 100644 --- a/src/function.c +++ b/src/function.c @@ -2109,7 +2109,7 @@ abspath (const char *name, char *apath) apath[3] = '/'; dest++; root_len++; - /* strncpy above copied one character too many. */ + /* memcpy above copied one character too many. */ name--; } else @@ -2178,13 +2178,13 @@ func_realpath (char *o, char **argv, const char *funcname UNUSED) { if (len < GET_PATH_MAX) { - char *rp; + char *rp, *inend; struct stat st; PATH_VAR (in); PATH_VAR (out); - strncpy (in, path, len); - in[len] = '\0'; + inend = mempcpy (in, path, len); + *inend = '\0'; #ifdef HAVE_REALPATH ENULLLOOP (rp, realpath (in, out)); @@ -2353,9 +2353,9 @@ func_abspath (char *o, char **argv, const char *funcname UNUSED) { PATH_VAR (in); PATH_VAR (out); + char *inend = mempcpy (in, path, len); - strncpy (in, path, len); - in[len] = '\0'; + *inend = '\0'; if (abspath (in, out)) { diff --git a/src/misc.c b/src/misc.c index 9e41a546..b36248f0 100644 --- a/src/misc.c +++ b/src/misc.c @@ -351,7 +351,7 @@ xstrndup (const char *str, size_t length) #else result = xmalloc (length + 1); if (length > 0) - strncpy (result, str, length); + memcpy (result, str, length); result[length] = '\0'; #endif