1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License, Version 1.0 only 6 * (the "License"). You may not use this file except in compliance 7 * with the License. 8 * 9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 10 * or http://www.opensolaris.org/os/licensing. 11 * See the License for the specific language governing permissions 12 * and limitations under the License. 13 * 14 * When distributing Covered Code, include this CDDL HEADER in each 15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 16 * If applicable, add the following below this CDDL HEADER, with the 17 * fields enclosed by brackets "[]" replaced with your own identifying 18 * information: Portions Copyright [yyyy] [name of copyright owner] 19 * 20 * CDDL HEADER END 21 */ 22 /* 23 * Copyright 2001-2002 Sun Microsystems, Inc. All rights reserved. 24 * Use is subject to license terms. 25 */ 26 27 #pragma ident "%Z%%M% %I% %E% SMI" 28 29 /* 30 * Routines for memory management 31 */ 32 33 #include <sys/types.h> 34 #include <stdio.h> 35 #include <stdlib.h> 36 #include <string.h> 37 #include <strings.h> 38 #include "memory.h" 39 40 static void 41 memory_bailout(void) 42 { 43 (void) fprintf(stderr, "Out of memory\n"); 44 exit(1); 45 } 46 47 int 48 xasprintf(char **s, const char *fmt, ...) 49 { 50 va_list ap; 51 int ret; 52 53 va_start(ap, fmt); 54 ret = vasprintf(s, fmt, ap); 55 va_end(ap); 56 if (ret == -1) 57 memory_bailout(); 58 return (ret); 59 } 60 61 void * 62 xmalloc(size_t size) 63 { 64 void *mem; 65 66 if ((mem = malloc(size)) == NULL) 67 memory_bailout(); 68 69 return (mem); 70 } 71 72 void * 73 xcalloc(size_t size) 74 { 75 void *mem; 76 77 mem = xmalloc(size); 78 bzero(mem, size); 79 80 return (mem); 81 } 82 83 char * 84 xstrdup(const char *str) 85 { 86 char *newstr; 87 88 if ((newstr = strdup(str)) == NULL) 89 memory_bailout(); 90 91 return (newstr); 92 } 93 94 char * 95 xstrndup(char *str, size_t len) 96 { 97 char *newstr; 98 99 if ((newstr = malloc(len + 1)) == NULL) 100 memory_bailout(); 101 102 (void) strncpy(newstr, str, len); 103 newstr[len] = '\0'; 104 105 return (newstr); 106 } 107 108 void * 109 xrealloc(void *ptr, size_t size) 110 { 111 void *mem; 112 113 if ((mem = realloc(ptr, size)) == NULL) 114 memory_bailout(); 115 116 return (mem); 117 } 118