]> pd.if.org Git - pdclib/blob - functions/string/strndup.c
* New feature check macro system. See _PDCLIB_aux.h for details
[pdclib] / functions / string / strndup.c
1 /* [XSI] char* strndup(const char *, size_t)\r
2 \r
3    This file is part of the Public Domain C Library (PDCLib).\r
4    Permission is granted to use, modify, and / or redistribute at will.\r
5 */\r
6 \r
7 #include <string.h>\r
8 #include <stdlib.h>\r
9 \r
10 #ifndef REGTEST\r
11 \r
12 char *strndup( const char * s, size_t len )\r
13 {\r
14     char* ns = NULL;\r
15     if(s) {\r
16         ns = malloc(len + 1);\r
17         if(ns) {\r
18             ns[len] = 0;\r
19             // strncpy to be pedantic about modification in multithreaded \r
20             // applications\r
21             return strncpy(ns, s, len);\r
22         }\r
23     }\r
24     return ns;\r
25 }\r
26 \r
27 #endif\r
28 \r
29 #ifdef TEST\r
30 #include <_PDCLIB_test.h>\r
31 \r
32 int main( void )\r
33 {\r
34     const char *teststr  = "Hello, world";\r
35     const char *teststr2 = "\xFE\x8C\n";\r
36     char *testres, *testres2;\r
37 \r
38     TESTCASE(testres  = strndup(teststr, 5));\r
39     TESTCASE(testres2 = strndup(teststr2, 1));\r
40     TESTCASE(strcmp(testres, teststr) != 0);\r
41     TESTCASE(strncmp(testres, teststr, 5) == 0);\r
42     TESTCASE(strcmp(testres2, teststr2) != 0);\r
43     TESTCASE(strncmp(testres2, teststr2, 1) == 0);\r
44     free(testres);\r
45     free(testres2);\r
46     TESTCASE(testres  = strndup(teststr, 20));\r
47     TESTCASE(testres2 = strndup(teststr2, 5));\r
48     TESTCASE(strcmp(testres, teststr) == 0);\r
49     TESTCASE(strcmp(testres2, teststr2) == 0);\r
50     free(testres);\r
51     free(testres2);\r
52     \r
53     return TEST_RESULTS;\r
54 }\r
55 \r
56 #endif\r