1 /* $NetBSD: xmalloc.c,v 1.2 2009/06/07 22:38:48 christos Exp $ */ 2 /* $OpenBSD: xmalloc.c,v 1.27 2006/08/03 03:34:42 deraadt Exp $ */ 3 /* 4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 6 * All rights reserved 7 * Versions of malloc and friends that check their results, and never return 8 * failure (they call fatal if they encounter an error). 9 * 10 * As far as I am concerned, the code I have written for this software 11 * can be used freely for any purpose. Any derived versions of this 12 * software must be clearly marked as such, and if the derived work is 13 * incompatible with the protocol description in the RFC file, it must be 14 * called by a name other than "ssh" or "Secure Shell". 15 */ 16 17 #include "includes.h" 18 __RCSID("$NetBSD: xmalloc.c,v 1.2 2009/06/07 22:38:48 christos Exp $"); 19 #include <sys/param.h> 20 #include <stdarg.h> 21 #include <stdio.h> 22 #include <stdlib.h> 23 #include <string.h> 24 25 #include "xmalloc.h" 26 #include "log.h" 27 28 void * 29 xmalloc(size_t size) 30 { 31 void *ptr; 32 33 if (size == 0) 34 fatal("xmalloc: zero size"); 35 ptr = malloc(size); 36 if (ptr == NULL) 37 fatal("xmalloc: out of memory (allocating %lu bytes)", (u_long) size); 38 return ptr; 39 } 40 41 void * 42 xcalloc(size_t nmemb, size_t size) 43 { 44 void *ptr; 45 46 if (size == 0 || nmemb == 0) 47 fatal("xcalloc: zero size"); 48 if (SIZE_T_MAX / nmemb < size) 49 fatal("xcalloc: nmemb * size > SIZE_T_MAX"); 50 ptr = calloc(nmemb, size); 51 if (ptr == NULL) 52 fatal("xcalloc: out of memory (allocating %lu bytes)", 53 (u_long)(size * nmemb)); 54 return ptr; 55 } 56 57 void * 58 xrealloc(void *ptr, size_t nmemb, size_t size) 59 { 60 void *new_ptr; 61 size_t new_size = nmemb * size; 62 63 if (new_size == 0) 64 fatal("xrealloc: zero size"); 65 if (SIZE_T_MAX / nmemb < size) 66 fatal("xrealloc: nmemb * size > SIZE_T_MAX"); 67 if (ptr == NULL) 68 new_ptr = malloc(new_size); 69 else 70 new_ptr = realloc(ptr, new_size); 71 if (new_ptr == NULL) 72 fatal("xrealloc: out of memory (new_size %lu bytes)", 73 (u_long) new_size); 74 return new_ptr; 75 } 76 77 void 78 xfree(void *ptr) 79 { 80 if (ptr == NULL) 81 fatal("xfree: NULL pointer given as argument"); 82 free(ptr); 83 } 84 85 char * 86 xstrdup(const char *str) 87 { 88 size_t len; 89 char *cp; 90 91 len = strlen(str) + 1; 92 cp = xmalloc(len); 93 strlcpy(cp, str, len); 94 return cp; 95 } 96 97 int 98 xasprintf(char **ret, const char *fmt, ...) 99 { 100 va_list ap; 101 int i; 102 103 va_start(ap, fmt); 104 i = vasprintf(ret, fmt, ap); 105 va_end(ap); 106 107 if (i < 0 || *ret == NULL) 108 fatal("xasprintf: could not allocate memory"); 109 110 return (i); 111 } 112