diff th_string.c @ 696:9bbacd72df3d

Allow src and dst to "overlap" for th_pstr_cpy().
author Matti Hamalainen <ccr@tnsp.org>
date Mon, 09 Mar 2020 19:13:52 +0200
parents 953e16582f25
children d687bbb54c1a
line wrap: on
line diff
--- a/th_string.c	Mon Mar 09 19:05:58 2020 +0200
+++ b/th_string.c	Mon Mar 09 19:13:52 2020 +0200
@@ -528,17 +528,19 @@
 int th_pstr_cpy(th_char_t **pdst, const th_char_t *src)
 {
     size_t slen;
+    th_char_t *tmp;
 
     if (pdst == NULL || src == NULL)
         return THERR_NULLPTR;
 
-    th_free(*pdst);
-
     slen = th_strlen(src);
-    if ((*pdst = th_malloc((slen + 1) * sizeof(th_char_t))) == NULL)
+    if ((tmp = th_malloc((slen + 1) * sizeof(th_char_t))) == NULL)
         return THERR_MALLOC;
 
-    memcpy(*pdst, src, (slen + 1) * sizeof(th_char_t));
+    memcpy(tmp, src, (slen + 1) * sizeof(th_char_t));
+
+    th_free(*pdst);
+    *pdst = tmp;
 
     return THERR_OK;
 }