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 * Copyright 2011-2012
9 * The Board of Trustees of the Leland Stanford Junior University
10 *
11 * Copying and distribution of this file, with or without modification, are
12 * permitted in any medium without royalty provided the copyright notice and
13 * this notice are preserved. This file is offered as-is, without any
14 * warranty.
15 *
16 * SPDX-License-Identifier: FSFAP
17 */
18
19 #include <config.h>
20 #include <portable/system.h>
21
22 #include <errno.h>
23
24 /*
25 * If we're running the test suite, rename the functions to avoid conflicts
26 * with the system versions.
27 */
28 #if TESTING
29 # undef strndup
30 # define strndup test_strndup
31 char *test_strndup(const char *, size_t);
32 #endif
33
34 char *
strndup(const char * s,size_t n)35 strndup(const char *s, size_t n)
36 {
37 const char *p;
38 size_t length;
39 char *copy;
40
41 if (s == NULL) {
42 errno = EINVAL;
43 return NULL;
44 }
45
46 /* Don't assume that the source string is nul-terminated. */
47 for (p = s; (size_t)(p - s) < n && *p != '\0'; p++)
48 ;
49 length = p - s;
50 copy = malloc(length + 1);
51 if (copy == NULL)
52 return NULL;
53 memcpy(copy, s, length);
54 copy[length] = '\0';
55 return copy;
56 }
57