zsh-workers
 help / color / mirror / code / Atom feed
* [PATCH] string.c: prefer memcpy() over strcpy()
@ 2023-12-31  5:43 James Tirta Halim
  2024-01-02  0:23 ` Bart Schaefer
  0 siblings, 1 reply; 3+ messages in thread
From: James Tirta Halim @ 2023-12-31  5:43 UTC (permalink / raw)
  To: zsh-workers; +Cc: James Tirta Halim

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



^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2024-01-02  4:28 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-12-31  5:43 [PATCH] string.c: prefer memcpy() over strcpy() James Tirta Halim
2024-01-02  0:23 ` Bart Schaefer
2024-01-02  4:23   ` James

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).