From c8fdd78cfb5ba3a2afcdbb95e69e49d1c0dc23ed Mon Sep 17 00:00:00 2001 From: j8takagi Date: Fri, 15 Feb 2019 21:51:08 +0900 Subject: [PATCH] =?utf8?q?strndup=5Fchk=E9=96=A2=E6=95=B0=E3=81=AE?= =?utf8?q?=E4=BF=AE=E6=AD=A3=E3=81=A8=E3=83=A6=E3=83=8B=E3=83=83=E3=83=88?= =?utf8?q?=E3=83=86=E3=82=B9=E3=83=88=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- src/cmem.c | 10 +++++++--- test/unit/strdup_chk/0.txt | 1 + test/unit/strdup_chk/Makefile | 20 ++++++++++++++++++++ test/unit/strdup_chk/cmd.c | 11 +++++++++++ 4 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 test/unit/strdup_chk/0.txt create mode 100644 test/unit/strdup_chk/Makefile create mode 100644 test/unit/strdup_chk/cmd.c 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; +} -- 2.18.0