]> eyrie.org Git - kerberos/krb5-strength.git/blob - portable/strndup.c
New upstream version 3.1
[kerberos/krb5-strength.git] / portable / strndup.c
1 /*
2  * Replacement for a missing strndup.
3  *
4  * The canonical version of this file is maintained in the rra-c-util package,
5  * which can be found at <https://www.eyrie.org/~eagle/software/rra-c-util/>.
6  *
7  * Written by Russ Allbery <eagle@eyrie.org>
8  *
9  * The authors hereby relinquish any claim to any copyright that they may have
10  * in this work, whether granted under contract or by operation of law or
11  * international treaty, and hereby commit to the public, at large, that they
12  * shall not, at any time in the future, seek to enforce any copyright in this
13  * work against any person or entity, or prevent any person or entity from
14  * copying, publishing, distributing or creating derivative works of this
15  * work.
16  */
17
18 #include <config.h>
19 #include <portable/system.h>
20
21 #include <errno.h>
22
23 /*
24  * If we're running the test suite, rename the functions to avoid conflicts
25  * with the system versions.
26  */
27 #if TESTING
28 # undef strndup
29 # define strndup test_strndup
30 char *test_strndup(const char *, size_t);
31 #endif
32
33 char *
34 strndup(const char *s, size_t n)
35 {
36     const char *p;
37     size_t length;
38     char *copy;
39
40     if (s == NULL) {
41         errno = EINVAL;
42         return NULL;
43     }
44
45     /* Don't assume that the source string is nul-terminated. */
46     for (p = s; (size_t) (p - s) < n && *p != '\0'; p++)
47         ;
48     length = p - s;
49     copy = malloc(length + 1);
50     if (copy == NULL)
51         return NULL;
52     memcpy(copy, s, length);
53     copy[length] = '\0';
54     return copy;
55 }