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