From 8368ba70fd164093ad84a2ada1bbfdefdabf20e1 Mon Sep 17 00:00:00 2001 From: Lephenixnoir Date: Sun, 23 May 2021 17:48:43 +0200 Subject: [PATCH] string: split and fix strdup and strndup (DONE) --- CMakeLists.txt | 1 + STATUS | 4 +-- src/libc/string/strdup.c | 64 +++------------------------------------ src/libc/string/strndup.c | 15 +++++++++ 4 files changed, 23 insertions(+), 61 deletions(-) create mode 100644 src/libc/string/strndup.c diff --git a/CMakeLists.txt b/CMakeLists.txt index cb2fc6e..4be5096 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -146,6 +146,7 @@ set(SOURCES src/libc/string/strncat.c src/libc/string/strncmp.c src/libc/string/strncpy.c + src/libc/string/strndup.c src/libc/string/strnlen.c src/libc/string/strrchr.c) diff --git a/STATUS b/STATUS index 92d272c..ee805ca 100644 --- a/STATUS +++ b/STATUS @@ -136,8 +136,8 @@ DONE: Function/symbol/macro is defined, builds, links, and is tested - strchrnul: DONE ! - strcasecmp: TODO ! - strncasecmp: TODO -! - strdup: TODO -! - strndup: TODO + - strdup: DONE + - strndup: DONE 7.22 => GCC diff --git a/src/libc/string/strdup.c b/src/libc/string/strdup.c index 2e532c6..575566b 100644 --- a/src/libc/string/strdup.c +++ b/src/libc/string/strdup.c @@ -1,64 +1,10 @@ #include #include -/* -** The strdup() function returns a pointer to a new string which is a -** duplicate of the string s. Memory for the new string is obtained with -** malloc(), and can be freed with free(). -*/ -char *strdup(const char *s) +char *strdup(char const *s) { - size_t len; - void *dump; - - // Check error - if (s == NULL) - return (NULL); - - // Check len - len = strlen(s); - if (len == 0) - return (NULL); - - // try to allocate the new area - dump = malloc(len); - if (dump == NULL) - return (NULL); - - // dump the area and return - memcpy(dump, s, len); - return (dump); + size_t len = strlen(s) + 1; + char *copy = malloc(len); + if(copy) memcpy(copy, s, len); + return copy; } - -/* -** The strndup() function is similar, but copies at most n bytes. If s is longer -** than n, only n bytes are copied, and a terminating null byte ('\0') is added. -*/ -char *strndump(const char *s, size_t n) -{ - size_t len; - char *dump; - - // Check error - if (s == NULL) - return (NULL); - - // Check len - len = strnlen(s, n); - if (len == 0) - return (NULL); - - // try to allocate the new area - dump = malloc(len); - if (dump == NULL) - return (NULL); - - // dump the area, set the null byte and return - memcpy(dump, s, len); - dump[len - 1] = '\0'; - return (dump); - -} - -//TODO: strdupa() -//TODO: strndupa() diff --git a/src/libc/string/strndup.c b/src/libc/string/strndup.c new file mode 100644 index 0000000..55f2012 --- /dev/null +++ b/src/libc/string/strndup.c @@ -0,0 +1,15 @@ +#include +#include + +char *strndup(const char *s, size_t n) +{ + size_t len = strnlen(s, n) + 1; + char *copy = malloc(len); + + if(copy) { + memcpy(copy, s, len); + copy[len - 1] = 0; + } + + return copy; +}