From 4d71c0ef04faa726195f9c0298a8677db1fc4f22 Mon Sep 17 00:00:00 2001 From: apio Date: Sat, 22 Oct 2022 17:49:44 +0200 Subject: [PATCH] libc: Implement strndup() --- libs/libc/include/string.h | 4 ++++ libs/libc/src/string.cpp | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/libs/libc/include/string.h b/libs/libc/include/string.h index d70ebbf6..5e495514 100644 --- a/libs/libc/include/string.h +++ b/libs/libc/include/string.h @@ -27,6 +27,10 @@ extern "C" /* Returns a heap-allocated copy of the string str. Should be freed when it is not used anymore. */ char* strdup(const char* str); + /* Returns a heap-allocated copy of the string str, copying at maximum max bytes. Should be freed when it is not + * used anymore. */ + char* strndup(const char* str, size_t max); + /* Returns the length of the string str. */ size_t strlen(const char* str); diff --git a/libs/libc/src/string.cpp b/libs/libc/src/string.cpp index 701821c2..85e0e8b3 100644 --- a/libs/libc/src/string.cpp +++ b/libs/libc/src/string.cpp @@ -54,6 +54,16 @@ extern "C" return (char*)memcpy(dest, str, len + 1); } + char* strndup(const char* str, size_t max) + { + size_t len = strnlen(str, max); + char* dest = (char*)malloc(len + 1); + if (!dest) return dest; + memcpy(dest, str, len); + dest[len] = 0; + return dest; + } + size_t strlen(const char* str) { const char* i = str;