From 18f59ad1ab72e5dea0386bd7811c3fcfb4cd7805 Mon Sep 17 00:00:00 2001 From: j8takagi Date: Sat, 9 Feb 2019 23:37:45 +0900 Subject: [PATCH] =?utf8?q?strndup=5Fchk=E9=96=A2=E6=95=B0=E3=81=A8?= =?utf8?q?=E3=83=A6=E3=83=8B=E3=83=83=E3=83=88=E3=83=86=E3=82=B9=E3=83=88?= =?utf8?q?=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- include/cmem.h | 10 ++++++++++ src/cmem.c | 11 +++++++++++ test/unit/strndup_chk/0.txt | 1 + test/unit/strndup_chk/Makefile | 20 ++++++++++++++++++++ test/unit/strndup_chk/cmd.c | 12 ++++++++++++ 5 files changed, 54 insertions(+) create mode 100644 test/unit/strndup_chk/0.txt create mode 100644 test/unit/strndup_chk/Makefile create mode 100644 test/unit/strndup_chk/cmd.c 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; +} -- 2.18.0