xref: /illumos-gate/usr/src/lib/libc/port/gen/strndup.c (revision 159a0043)
123a1cceaSRoger A. Faulkner /*
223a1cceaSRoger A. Faulkner  * CDDL HEADER START
323a1cceaSRoger A. Faulkner  *
423a1cceaSRoger A. Faulkner  * The contents of this file are subject to the terms of the
523a1cceaSRoger A. Faulkner  * Common Development and Distribution License (the "License").
623a1cceaSRoger A. Faulkner  * You may not use this file except in compliance with the License.
723a1cceaSRoger A. Faulkner  *
823a1cceaSRoger A. Faulkner  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
923a1cceaSRoger A. Faulkner  * or http://www.opensolaris.org/os/licensing.
1023a1cceaSRoger A. Faulkner  * See the License for the specific language governing permissions
1123a1cceaSRoger A. Faulkner  * and limitations under the License.
1223a1cceaSRoger A. Faulkner  *
1323a1cceaSRoger A. Faulkner  * When distributing Covered Code, include this CDDL HEADER in each
1423a1cceaSRoger A. Faulkner  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
1523a1cceaSRoger A. Faulkner  * If applicable, add the following below this CDDL HEADER, with the
1623a1cceaSRoger A. Faulkner  * fields enclosed by brackets "[]" replaced with your own identifying
1723a1cceaSRoger A. Faulkner  * information: Portions Copyright [yyyy] [name of copyright owner]
1823a1cceaSRoger A. Faulkner  *
1923a1cceaSRoger A. Faulkner  * CDDL HEADER END
2023a1cceaSRoger A. Faulkner  */
2123a1cceaSRoger A. Faulkner 
2223a1cceaSRoger A. Faulkner /*
2323a1cceaSRoger A. Faulkner  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
24*159a0043SBryan Cantrill  * Copyright 2018 Joyent, Inc.
2523a1cceaSRoger A. Faulkner  */
2623a1cceaSRoger A. Faulkner 
2723a1cceaSRoger A. Faulkner #include "lint.h"
2823a1cceaSRoger A. Faulkner #include <string.h>
29*159a0043SBryan Cantrill #include <strings.h>
3023a1cceaSRoger A. Faulkner #include <stdlib.h>
3123a1cceaSRoger A. Faulkner #include <sys/types.h>
3223a1cceaSRoger A. Faulkner 
3323a1cceaSRoger A. Faulkner /*
3423a1cceaSRoger A. Faulkner  * Create a copy of string s, but only duplicate the first n bytes.
3523a1cceaSRoger A. Faulkner  * Return NULL if the new string can't be allocated.
3623a1cceaSRoger A. Faulkner  */
3723a1cceaSRoger A. Faulkner char *
strndup(const char * s1,size_t n)3823a1cceaSRoger A. Faulkner strndup(const char *s1, size_t n)
3923a1cceaSRoger A. Faulkner {
4023a1cceaSRoger A. Faulkner 	char *s2;
4123a1cceaSRoger A. Faulkner 
4223a1cceaSRoger A. Faulkner 	n = strnlen(s1, n);
43*159a0043SBryan Cantrill 	if ((s2 = malloc(n + 1)) != NULL) {
44*159a0043SBryan Cantrill 		bcopy(s1, s2, n);
45*159a0043SBryan Cantrill 		s2[n] = '\0';
46*159a0043SBryan Cantrill 	}
47*159a0043SBryan Cantrill 
4823a1cceaSRoger A. Faulkner 	return (s2);
4923a1cceaSRoger A. Faulkner }
50