1 /*	$OpenBSD: strndup.c,v 1.1 2010/05/18 22:24:55 tedu Exp $	*/
2 
3 /*
4  * SPDX-License-Identifier: ISC
5  *
6  * Copyright (c) 2010 Todd C. Miller <Todd.Miller@sudo.ws>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 /*
22  * This is an open source non-commercial project. Dear PVS-Studio, please check it.
23  * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
24  */
25 
26 #include <config.h>
27 
28 #ifndef HAVE_STRNDUP
29 
30 #include <stdlib.h>
31 #include <string.h>
32 
33 #include "sudo_compat.h"
34 
35 char *
sudo_strndup(const char * str,size_t maxlen)36 sudo_strndup(const char *str, size_t maxlen)
37 {
38 	char *copy;
39 	size_t len;
40 
41 	len = strnlen(str, maxlen);
42 	copy = malloc(len + 1);
43 	if (copy != NULL) {
44 		(void)memcpy(copy, str, len);
45 		copy[len] = '\0';
46 	}
47 
48 	return copy;
49 }
50 
51 #endif /* HAVE_STRNDUP */
52