libc: Implement strndup()

This commit is contained in:
apio 2022-10-22 17:49:44 +02:00
parent 20429929dd
commit 4d71c0ef04
2 changed files with 14 additions and 0 deletions

View File

@ -27,6 +27,10 @@ extern "C"
/* Returns a heap-allocated copy of the string str. Should be freed when it is not used anymore. */ /* Returns a heap-allocated copy of the string str. Should be freed when it is not used anymore. */
char* strdup(const char* str); 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. */ /* Returns the length of the string str. */
size_t strlen(const char* str); size_t strlen(const char* str);

View File

@ -54,6 +54,16 @@ extern "C"
return (char*)memcpy(dest, str, len + 1); 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) size_t strlen(const char* str)
{ {
const char* i = str; const char* i = str;