]> pd.if.org Git - pdclib/blob - functions/string/strndup.c
Type mismatches give compiler warnings. Fixed.
[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 #ifndef REGTEST\r
35     /* Missing on Windows. Maybe use conditionals? */\r
36     const char *teststr  = "Hello, world";\r
37     const char *teststr2 = "\xFE\x8C\n";\r
38     char *testres, *testres2;\r
39 \r
40     TESTCASE((testres  = strndup(teststr, 5)) != NULL);\r
41     TESTCASE((testres2 = strndup(teststr2, 1)) != NULL);\r
42     TESTCASE(strcmp(testres, teststr) != 0);\r
43     TESTCASE(strncmp(testres, teststr, 5) == 0);\r
44     TESTCASE(strcmp(testres2, teststr2) != 0);\r
45     TESTCASE(strncmp(testres2, teststr2, 1) == 0);\r
46     free(testres);\r
47     free(testres2);\r
48     TESTCASE((testres  = strndup(teststr, 20)) != NULL);\r
49     TESTCASE((testres2 = strndup(teststr2, 5)) != NULL);\r
50     TESTCASE(strcmp(testres, teststr) == 0);\r
51     TESTCASE(strcmp(testres2, teststr2) == 0);\r
52     free(testres);\r
53     free(testres2);\r
54 #endif\r
55 \r
56     return TEST_RESULTS;\r
57 }\r
58 \r
59 #endif\r