strndup_chk関数とユニットテストを追加
authorj8takagi <j8takagi@nifty.com>
Sat, 9 Feb 2019 14:37:45 +0000 (23:37 +0900)
committerj8takagi <j8takagi@nifty.com>
Sat, 9 Feb 2019 14:38:21 +0000 (23:38 +0900)
include/cmem.h
src/cmem.c
test/unit/strndup_chk/0.txt [new file with mode: 0644]
test/unit/strndup_chk/Makefile [new file with mode: 0644]
test/unit/strndup_chk/cmd.c [new file with mode: 0644]

index 132ef28..fca5acb 100644 (file)
@@ -56,4 +56,14 @@ void *calloc_chk(size_t nmemb, size_t size, char *tag);
  */
 char *strdup_chk(const char *s, char *tag);
 
+/**
+ * @brief malloc_chkを実行してメモリを確保し、コピーした文字列の指定した長さの部分を返す
+ *
+ * @return コピーした文字列
+ *
+ * @param s 文字列
+ * @param len 文字列の長さ
+ * @param tag エラーメッセージなどで表示されるタグ
+ */
+char *strndup_chk(const char *s, size_t len, char *tag);
 #endif
index 4e24586..ef7a9dd 100644 (file)
@@ -31,3 +31,14 @@ char *strdup_chk(const char *s, char *tag)
     strcpy(t, s);
     return t;
 }
+
+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';
+    return t;
+}
diff --git a/test/unit/strndup_chk/0.txt b/test/unit/strndup_chk/0.txt
new file mode 100644 (file)
index 0000000..4b51ddb
--- /dev/null
@@ -0,0 +1 @@
+abcdefghij
diff --git a/test/unit/strndup_chk/Makefile b/test/unit/strndup_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/strndup_chk/cmd.c b/test/unit/strndup_chk/cmd.c
new file mode 100644 (file)
index 0000000..d5f82b5
--- /dev/null
@@ -0,0 +1,12 @@
+#include <stdio.h>
+#include "cmem.h"
+
+int main(){
+    char *dst, *src = "abcdefghijklmnopqrstuvwxyz";
+    size_t len = 10;
+
+    dst = strndup_chk(src, len, "strndup_chk unit test");
+    printf("%s\n", dst);
+    FREE(dst);
+    return 0;
+}