xref: /freebsd/contrib/mandoc/compat_strndup.c (revision eda14cbc264d6969b02f2b1994cef11148e914f1)
1 #include "config.h"
2 
3 #if HAVE_STRNDUP
4 
5 int dummy;
6 
7 #else
8 
9 /* $Id: compat_strndup.c,v 1.1 2018/02/27 11:16:23 schwarze Exp $ */
10 /* OpenBSD: strndup.c,v 1.2 2015/08/31 02:53:57 guenther Exp */
11 /*
12  * Copyright (c) 2010 Todd C. Miller <Todd.Miller@courtesan.com>
13  *
14  * Permission to use, copy, modify, and distribute this software for any
15  * purpose with or without fee is hereby granted, provided that the above
16  * copyright notice and this permission notice appear in all copies.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
19  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
20  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
21  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
22  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
23  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
24  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
25  */
26 
27 #include <sys/types.h>
28 
29 #include <stdlib.h>
30 #include <string.h>
31 
32 char *
33 strndup(const char *str, size_t maxlen)
34 {
35 	char *copy;
36 	size_t len;
37 
38 	for (len = 0; len < maxlen && str[len] != '\0'; len++)
39 		continue;
40 
41 	copy = malloc(len + 1);
42 	if (copy != NULL) {
43 		(void)memcpy(copy, str, len);
44 		copy[len] = '\0';
45 	}
46 
47 	return copy;
48 }
49 
50 #endif
51