1 /*
2  * Copyright 2003,2004 Red Hat, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, and the entire permission notice in its entirety,
9  *    including the disclaimer of warranties.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote
14  *    products derived from this software without specific prior
15  *    written permission.
16  *
17  * ALTERNATIVELY, this product may be distributed under the terms of the
18  * GNU Lesser General Public License, in which case the provisions of the
19  * LGPL are required INSTEAD OF the above restrictions.
20  *
21  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
22  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
23  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
24  * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
27  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
28  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #include "../config.h"
34 
35 #include <stdlib.h>
36 #include <string.h>
37 #include "xstr.h"
38 
39 int
xstrlen(const char * s)40 xstrlen(const char *s)
41 {
42 	if (s != NULL) {
43 		return strlen(s);
44 	}
45 	return 0;
46 }
47 
48 void
xstrfree(char * s)49 xstrfree(char *s)
50 {
51 	if (s != NULL) {
52 		memset(s, '\0', strlen(s));
53 		free(s);
54 	}
55 }
56 
57 char *
xstrdup(const char * s)58 xstrdup(const char *s)
59 {
60 	char *ret;
61 	int len;
62 	len = xstrlen(s);
63 	ret = malloc(len + 1);
64 	if (ret != NULL) {
65 		memset(ret, '\0', len + 1);
66 		if (s != NULL) {
67 			strcpy(ret, s);
68 		}
69 	}
70 	return ret;
71 }
72 
73 char *
xstrndup(const char * s,int n)74 xstrndup(const char *s, int n)
75 {
76 	char *ret;
77 	int len;
78 	len = xstrlen(s);
79 	ret = malloc(len + 1);
80 	if (ret != NULL) {
81 		memset(ret, '\0', len + 1);
82 		if (s != NULL) {
83 			if (n < len) {
84 				memmove(ret, s, n);
85 			} else {
86 				memmove(ret, s, len);
87 			}
88 		}
89 	}
90 	return ret;
91 }
92