xref: /haiku/src/system/libroot/posix/string/strndup.cpp (revision 1e60bdeab63fa7a57bc9a55b032052e95a18bd2c)
1 /*
2  * Copyright 2009, Axel Dörfler, axeld@pinc-software.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include <string.h>
8 #include <stdlib.h>
9 
10 
11 extern "C" char*
12 strndup(const char* string, size_t size)
13 {
14 	// While POSIX does not mention it, we handle NULL pointers gracefully
15 	if (string == NULL)
16 		return NULL;
17 
18 	size_t length = strlen(string);
19 	if (length > size)
20 		length = size;
21 
22 	char* copied = (char*)malloc(length + 1);
23 	if (copied == NULL)
24 		return NULL;
25 
26 	memcpy(copied, string, length);
27 	copied[length] = '\0';
28 
29 	return copied;
30 }
31