Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

[PATCH] string.c: prefer memcpy() over strcpy()



Add STRCPY_WLEN, a memcpy() that nul-terminates.

---
 Src/string.c | 19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)

diff --git a/Src/string.c b/Src/string.c
index 5f439926e..fc85da183 100644
--- a/Src/string.c
+++ b/Src/string.c
@@ -28,6 +28,8 @@
 
 #include "zsh.mdh"
 
+#define STRCPY_WLEN(dst, src, n) (void)(*((char *)memcpy(dst, src, n) + n) = '\0')
+
 /**/
 mod_export char *
 dupstring(const char *s)
@@ -36,8 +38,9 @@ dupstring(const char *s)
 
     if (!s)
 	return NULL;
-    t = (char *) zhalloc(strlen((char *)s) + 1);
-    strcpy(t, s);
+    const size_t s_len = strlen((char *)s);
+    t = (char *) zhalloc(s_len + 1);
+    STRCPY_WLEN(t, s, s_len);
     return t;
 }
 
@@ -80,8 +83,9 @@ ztrdup(const char *s)
 
     if (!s)
 	return NULL;
-    t = (char *)zalloc(strlen((char *)s) + 1);
-    strcpy(t, s);
+    const size_t s_len = strlen((char *)s);
+    t = (char *)zalloc(s_len + 1);
+    STRCPY_WLEN(t, s, s_len);
     return t;
 }
 
@@ -148,10 +152,11 @@ dyncat(const char *s1, const char *s2)
     /* This version always uses space from the current heap. */
     char *ptr;
     size_t l1 = strlen(s1);
+    size_t l2 = strlen(s2);
 
-    ptr = (char *)zhalloc(l1 + strlen(s2) + 1);
-    strcpy(ptr, s1);
-    strcpy(ptr + l1, s2);
+    ptr = (char *)zhalloc(l1 + l2 + 1);
+    memcpy(ptr, s1, l1);
+    STRCPY_WLEN(ptr + l1, s2, l2);
     return ptr;
 }
 
-- 
2.43.0





Messages sorted by: Reverse Date, Date, Thread, Author