From: j8takagi Date: Fri, 15 Feb 2019 12:51:08 +0000 (+0900) Subject: strndup_chk関数の修正とユニットテスト追加 X-Git-Tag: v0.5p5~6 X-Git-Url: https://j8takagi.net/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c8fdd78cfb5ba3a2afcdbb95e69e49d1c0dc23ed;p=YACASL2.git strndup_chk関数の修正とユニットテスト追加 --- diff --git a/src/cmem.c b/src/cmem.c index ef7a9dd..17535d8 100644 --- a/src/cmem.c +++ b/src/cmem.c @@ -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 index 0000000..b0883f3 --- /dev/null +++ b/test/unit/strdup_chk/0.txt @@ -0,0 +1 @@ +abcdefghijklmnopqrstuvwxyz diff --git a/test/unit/strdup_chk/Makefile b/test/unit/strdup_chk/Makefile new file mode 100644 index 0000000..c9ff667 --- /dev/null +++ b/test/unit/strdup_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/strdup_chk/cmd.c b/test/unit/strdup_chk/cmd.c new file mode 100644 index 0000000..36d43c5 --- /dev/null +++ b/test/unit/strdup_chk/cmd.c @@ -0,0 +1,11 @@ +#include +#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; +}