make_malloc.c revision 1.1
1/* $NetBSD: make_malloc.c,v 1.1 2009/01/24 11:59:39 dsl 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.1 2009/01/24 11:59:39 dsl Exp $"); 31 32#include <sys/types.h> 33#include <stdio.h> 34#include <stdlib.h> 35 36#ifndef USE_EMALLOC 37/* 38 * enomem -- 39 * die when out of memory. 40 */ 41static void 42enomem(void) 43{ 44 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno)); 45 exit(2); 46} 47 48/* 49 * bmake_malloc -- 50 * malloc, but die on error. 51 */ 52void * 53bmake_malloc(size_t len) 54{ 55 void *p; 56 57 if ((p = malloc(len)) == NULL) 58 enomem(); 59 return(p); 60} 61 62/* 63 * bmake_strdup -- 64 * strdup, but die on error. 65 */ 66char * 67bmake_strdup(const char *str) 68{ 69 size_t len; 70 char *p; 71 72 len = strlen(str) + 1; 73 if ((p = malloc(len)) == NULL) 74 enomem(); 75 return memcpy(p, str, len); 76} 77 78/* 79 * bmake_strndup -- 80 * strndup, but die on error. 81 */ 82char * 83bmake_strndup(const char *str, size_t max_len) 84{ 85 size_t len; 86 char *p; 87 88 if (str == NULL) 89 return NULL; 90 91 len = strlen(str); 92 if (len > max_len) 93 len = max_len; 94 p = bmake_malloc(len + 1); 95 memcpy(p, str, len); 96 p[len] = '\0'; 97 98 return(p); 99} 100 101/* 102 * bmake_realloc -- 103 * realloc, but die on error. 104 */ 105void * 106bmake_realloc(void *ptr, size_t size) 107{ 108 if ((ptr = realloc(ptr, size)) == NULL) 109 enomem(); 110 return(ptr); 111} 112#endif 113