]> pd.if.org Git - pdclib/blob - functions/string/strdup.c
dos2unix
[pdclib] / functions / string / strdup.c
1 /* [XSI] char * strdup( const char * )
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 *strdup(const char *s)
17 {
18     char* ns = NULL;
19     if(s) {
20         size_t len = strlen(s) + 1;
21         ns = malloc(len);
22         if(ns)
23             strncpy(ns, s, len);
24     }
25     return ns;
26 }
27
28 #endif
29
30 #ifdef TEST
31 #include "_PDCLIB_test.h"
32
33 int main( void )
34 {
35     const char *teststr  = "Hello, world";
36     const char *teststr2 = "An alternative test string with non-7-bit characters \xFE\x8C\n";
37     char *testres, *testres2;
38
39     TESTCASE((testres  = strdup(teststr)) != NULL);
40     TESTCASE((testres2 = strdup(teststr2)) != NULL);
41     TESTCASE(strcmp(testres, teststr) == 0);
42     TESTCASE(strcmp(testres2, teststr2) == 0);
43     free(testres);
44     free(testres2);
45
46     return TEST_RESULTS;
47 }
48
49 #endif