strndup_chk関数の修正とユニットテスト追加
authorj8takagi <j8takagi@nifty.com>
Fri, 15 Feb 2019 12:51:08 +0000 (21:51 +0900)
committerj8takagi <j8takagi@nifty.com>
Fri, 15 Feb 2019 12:51:08 +0000 (21:51 +0900)
src/cmem.c
test/unit/strdup_chk/0.txt [new file with mode: 0644]
test/unit/strdup_chk/Makefile [new file with mode: 0644]
test/unit/strdup_chk/cmd.c [new file with mode: 0644]

index ef7a9dd..17535d8 100644 (file)
@@ -37,8 +37,12 @@ char *strndup_chk(const char *s, size_t len, char *tag)
     assert(s != NULL);
     char *t;
 
-    t = malloc_chk(len + 1, tag);
-    strncpy(t, s, len);
-    t[len] = '\0';
+    if(len < strlen(s)) {
+        t = malloc_chk(len + 1, tag);
+        strncpy(t, s, len);
+        t[len] = '\0';
+    } else {
+        t = strdup_chk(s, tag);
+    }
     return t;
 }
diff --git a/test/unit/strdup_chk/0.txt b/test/unit/strdup_chk/0.txt
new file mode 100644 (file)
index 0000000..b0883f3
--- /dev/null
@@ -0,0 +1 @@
+abcdefghijklmnopqrstuvwxyz
diff --git a/test/unit/strdup_chk/Makefile b/test/unit/strdup_chk/Makefile
new file mode 100644 (file)
index 0000000..c9ff667
--- /dev/null
@@ -0,0 +1,20 @@
+include ../Define.mk
+include ../Test.mk
+
+CC := gcc
+CFLAGS := -Wall
+
+.INTERMEDIATE: $(CMD_FILE)
+
+CMDSRC_FILE := cmd.c
+TARGETDIR := ../../../src
+INCLUDEDIR := ../../../include
+TESTTARGET_FILES := $(TARGETDIR)/cmem.c         # Set test target files
+
+$(CMD_FILE): $(CMDSRC_FILE) $(TESTTARGET_FILES)
+       $(CC) $(CFLAGS) -I $(INCLUDEDIR) -o $@ $^
+
+clean_cmd:
+       @rm -rf cmd.dSYM cmd
+
+clean: clean_cmd
diff --git a/test/unit/strdup_chk/cmd.c b/test/unit/strdup_chk/cmd.c
new file mode 100644 (file)
index 0000000..36d43c5
--- /dev/null
@@ -0,0 +1,11 @@
+#include <stdio.h>
+#include "cmem.h"
+
+int main(){
+    char *dst, *src = "abcdefghijklmnopqrstuvwxyz";
+
+    dst = strdup_chk(src, "strdup_chk unit test");
+    printf("%s\n", dst);
+    FREE(dst);
+    return 0;
+}