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