From: j8takagi Date: Sat, 9 Feb 2019 14:37:45 +0000 (+0900) Subject: strndup_chk関数とユニットテストを追加 X-Git-Tag: v0.5p3~9 X-Git-Url: https://j8takagi.net/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=18f59ad1ab72e5dea0386bd7811c3fcfb4cd7805;p=YACASL2.git strndup_chk関数とユニットテストを追加 --- diff --git a/include/cmem.h b/include/cmem.h index 132ef28..fca5acb 100644 --- a/include/cmem.h +++ b/include/cmem.h @@ -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 diff --git a/src/cmem.c b/src/cmem.c index 4e24586..ef7a9dd 100644 --- a/src/cmem.c +++ b/src/cmem.c @@ -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 index 0000000..4b51ddb --- /dev/null +++ b/test/unit/strndup_chk/0.txt @@ -0,0 +1 @@ +abcdefghij diff --git a/test/unit/strndup_chk/Makefile b/test/unit/strndup_chk/Makefile new file mode 100644 index 0000000..c9ff667 --- /dev/null +++ b/test/unit/strndup_chk/Makefile @@ -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 index 0000000..d5f82b5 --- /dev/null +++ b/test/unit/strndup_chk/cmd.c @@ -0,0 +1,12 @@ +#include +#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; +}