]> pd.if.org Git - pdclib/blob - functions/string/strndup.c
RegTest gives warning about implicitly declared functions. 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 #ifdef REGTEST\r
8 #define _POSIX_C_SOURCE 200809L\r
9 #endif\r
10 \r
11 #include <string.h>\r
12 #include <stdlib.h>\r
13 \r
14 #ifndef REGTEST\r
15 \r
16 char *strndup( const char * s, size_t len )\r
17 {\r
18     char* ns = NULL;\r
19     if(s) {\r
20         ns = malloc(len + 1);\r
21         if(ns) {\r
22             ns[len] = 0;\r
23             // strncpy to be pedantic about modification in multithreaded \r
24             // applications\r
25             return strncpy(ns, s, len);\r
26         }\r
27     }\r
28     return ns;\r
29 }\r
30 \r
31 #endif\r
32 \r
33 #ifdef TEST\r
34 #include <_PDCLIB_test.h>\r
35 \r
36 int main( void )\r
37 {\r
38 #ifndef REGTEST\r
39     /* Missing on Windows. Maybe use conditionals? */\r
40     const char *teststr  = "Hello, world";\r
41     const char *teststr2 = "\xFE\x8C\n";\r
42     char *testres, *testres2;\r
43 \r
44     TESTCASE((testres  = strndup(teststr, 5)) != NULL);\r
45     TESTCASE((testres2 = strndup(teststr2, 1)) != NULL);\r
46     TESTCASE(strcmp(testres, teststr) != 0);\r
47     TESTCASE(strncmp(testres, teststr, 5) == 0);\r
48     TESTCASE(strcmp(testres2, teststr2) != 0);\r
49     TESTCASE(strncmp(testres2, teststr2, 1) == 0);\r
50     free(testres);\r
51     free(testres2);\r
52     TESTCASE((testres  = strndup(teststr, 20)) != NULL);\r
53     TESTCASE((testres2 = strndup(teststr2, 5)) != NULL);\r
54     TESTCASE(strcmp(testres, teststr) == 0);\r
55     TESTCASE(strcmp(testres2, teststr2) == 0);\r
56     free(testres);\r
57     free(testres2);\r
58 #endif\r
59 \r
60     return TEST_RESULTS;\r
61 }\r
62 \r
63 #endif\r