X-Git-Url: https://pd.if.org/git/?p=pdclib;a=blobdiff_plain;f=functions%2Fstring%2Fstrndup.c;fp=functions%2Fstring%2Fstrndup.c;h=e25c7ed967855955b824c27443f4f31817abc44f;hp=0000000000000000000000000000000000000000;hb=1cc4363093c919f79eafac209bb5c41548d3f88f;hpb=5155ca96295a12b4857fc0e6a9629cc43a9a85fa diff --git a/functions/string/strndup.c b/functions/string/strndup.c new file mode 100644 index 0000000..e25c7ed --- /dev/null +++ b/functions/string/strndup.c @@ -0,0 +1,56 @@ +/* [XSI] char* strndup(const char *, size_t) + + This file is part of the Public Domain C Library (PDCLib). + Permission is granted to use, modify, and / or redistribute at will. +*/ + +#include +#include + +#ifndef REGTEST + +char *strndup( const char * s, size_t len ) +{ + char* ns = NULL; + if(s) { + ns = malloc(len + 1); + if(ns) { + ns[len] = 0; + // strncpy to be pedantic about modification in multithreaded + // applications + return strncpy(ns, s, len); + } + } + return ns; +} + +#endif + +#ifdef TEST +#include <_PDCLIB_test.h> + +int main( void ) +{ + const char *teststr = "Hello, world"; + const char *teststr2 = "\xFE\x8C\n"; + char *testres, *testres2; + + TESTCASE(testres = strndup(teststr, 5)); + TESTCASE(testres2 = strndup(teststr2, 1)); + TESTCASE(strcmp(testres, teststr) != 0); + TESTCASE(strncmp(testres, teststr, 5) == 0); + TESTCASE(strcmp(testres2, teststr2) != 0); + TESTCASE(strncmp(testres2, teststr2, 1) == 0); + free(testres); + free(testres2); + TESTCASE(testres = strndup(teststr, 20)); + TESTCASE(testres2 = strndup(teststr2, 5)); + TESTCASE(strcmp(testres, teststr) == 0); + TESTCASE(strcmp(testres2, teststr2) == 0); + free(testres); + free(testres2); + + return TEST_RESULTS; +} + +#endif