diff --git a/headers/posix/string.h b/headers/posix/string.h index aec0079488..f7a13a2f92 100644 --- a/headers/posix/string.h +++ b/headers/posix/string.h @@ -1,5 +1,5 @@ /* - * Copyright 2004, Haiku Inc. All Rights Reserved. + * Copyright 2004-2009, Haiku Inc. All Rights Reserved. * Distributed under the terms of the MIT License. */ #ifndef _STRING_H_ @@ -58,6 +58,7 @@ extern int strncasecmp(const char *string1, const char *string2, size_t length) extern char *strcasestr(const char *string, const char *searchString); extern char *strdup(const char *string); +extern char *strndup(const char* string, size_t size); extern char *stpcpy(char *dest, const char *source); extern size_t strlcat(char *dest, const char *source, size_t length); diff --git a/src/system/libroot/posix/string/Jamfile b/src/system/libroot/posix/string/Jamfile index 0cdc07efc3..f4435c85a4 100644 --- a/src/system/libroot/posix/string/Jamfile +++ b/src/system/libroot/posix/string/Jamfile @@ -27,6 +27,7 @@ MergeObject posix_string.o : strncat.c strncmp.c strncpy.c + strndup.cpp strnlen.c strpbrk.c strrchr.c diff --git a/src/system/libroot/posix/string/strndup.cpp b/src/system/libroot/posix/string/strndup.cpp new file mode 100644 index 0000000000..94dc45e1dc --- /dev/null +++ b/src/system/libroot/posix/string/strndup.cpp @@ -0,0 +1,30 @@ +/* + * Copyright 2009, Axel Dörfler, axeld@pinc-software.de. + * Distributed under the terms of the MIT License. + */ + + +#include +#include + + +extern "C" char* +strndup(const char* string, size_t size) +{ + // While POSIX does not mention it, we handle NULL pointers gracefully + if (string == NULL) + return NULL; + + size_t length = strlen(string); + if (length > size) + length = size; + + char* copied = (char*)malloc(length + 1); + if (copied == NULL) + return NULL; + + memcpy(copied, string, length); + copied[length] = '\0'; + + return copied; +}