* Re-implemented str_ncpy() without the use of strncat() to avoid -Werror=stringop... master
authorUrban Wallasch <urban.wallasch@freenet.de>
Thu, 23 Apr 2020 09:19:25 +0000 (11:19 +0200)
committerUrban Wallasch <urban.wallasch@freenet.de>
Thu, 23 Apr 2020 09:19:25 +0000 (11:19 +0200)
str/str.h
str/str_test.c

index 0005b8bb5fac845497511e4cb66534ea748c4e80..4736ce44b6e2127366f10294603c189f0e3b4bba 100644 (file)
--- a/str/str.h
+++ b/str/str.h
@@ -475,8 +475,12 @@ static inline size_t str_nlen(const char *s, size_t maxlen) {
  * The buffer dest must be large enough to hold at least n+1 characters.
  */
 static inline char *str_ncpy(char *dest, const char *src, size_t n) {
  * The buffer dest must be large enough to hold at least n+1 characters.
  */
 static inline char *str_ncpy(char *dest, const char *src, size_t n) {
-    *dest = '\0';
-    return strncat(dest, src, n);
+    char *d = dest;
+
+    while ( *src && n-- )
+        *d++ = *src++;
+    *d = '\0';
+    return dest;
 }
 
 
 }
 
 
index 3520fd1811435dbd476a5c4683e4c8ef96285021..5a807bffd63c7f2b18e3e8113bd1beeff7155072 100644 (file)
@@ -400,7 +400,11 @@ int main(void) {
 
     {
         H("str_ncpy");
 
     {
         H("str_ncpy");
-        char s[11] = { 0 };
+        char s[11] = "_deadbeef_";
+        D(s);
+        T(strcmp(str_ncpy(s, "foobar", 0), "") == 0);
+        D(s);
+        T(strcmp(str_ncpy(s, "foobar", 1), "f") == 0);
         D(s);
         T(strcmp(str_ncpy(s, "foobar", 10), "foobar") == 0);
         D(s);
         D(s);
         T(strcmp(str_ncpy(s, "foobar", 10), "foobar") == 0);
         D(s);