make_malloc.c revision 1.2 1 /* $NetBSD: make_malloc.c,v 1.2 2009/01/24 13:06:16 cegger Exp $ */
2
3 /*-
4 * Copyright (c) 2009 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 #include <sys/cdefs.h>
30 __RCSID("$NetBSD: make_malloc.c,v 1.2 2009/01/24 13:06:16 cegger Exp $");
31
32 #include <sys/types.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <errno.h>
37
38 #ifndef USE_EMALLOC
39 /*
40 * enomem --
41 * die when out of memory.
42 */
43 static void
44 enomem(void)
45 {
46 (void)fprintf(stderr, "%s.\n", strerror(errno));
47 exit(2);
48 }
49
50 /*
51 * bmake_malloc --
52 * malloc, but die on error.
53 */
54 void *
55 bmake_malloc(size_t len)
56 {
57 void *p;
58
59 if ((p = malloc(len)) == NULL)
60 enomem();
61 return(p);
62 }
63
64 /*
65 * bmake_strdup --
66 * strdup, but die on error.
67 */
68 char *
69 bmake_strdup(const char *str)
70 {
71 size_t len;
72 char *p;
73
74 len = strlen(str) + 1;
75 if ((p = malloc(len)) == NULL)
76 enomem();
77 return memcpy(p, str, len);
78 }
79
80 /*
81 * bmake_strndup --
82 * strndup, but die on error.
83 */
84 char *
85 bmake_strndup(const char *str, size_t max_len)
86 {
87 size_t len;
88 char *p;
89
90 if (str == NULL)
91 return NULL;
92
93 len = strlen(str);
94 if (len > max_len)
95 len = max_len;
96 p = bmake_malloc(len + 1);
97 memcpy(p, str, len);
98 p[len] = '\0';
99
100 return(p);
101 }
102
103 /*
104 * bmake_realloc --
105 * realloc, but die on error.
106 */
107 void *
108 bmake_realloc(void *ptr, size_t size)
109 {
110 if ((ptr = realloc(ptr, size)) == NULL)
111 enomem();
112 return(ptr);
113 }
114 #endif
115