1 /* $OpenBSD: xmalloc.c,v 1.1 2007/05/29 18:24:56 ray Exp $ */ 2 /* 3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 5 * All rights reserved 6 * Versions of malloc and friends that check their results, and never return 7 * failure (they call fatal if they encounter an error). 8 * 9 * As far as I am concerned, the code I have written for this software 10 * can be used freely for any purpose. Any derived versions of this 11 * software must be clearly marked as such, and if the derived work is 12 * incompatible with the protocol description in the RFC file, it must be 13 * called by a name other than "ssh" or "Secure Shell". 14 */ 15 16 #include <err.h> 17 #include <limits.h> 18 #include <stdarg.h> 19 #include <stdio.h> 20 #include <stdlib.h> 21 #include <string.h> 22 23 #include "xmalloc.h" 24 25 void * 26 xmalloc(size_t size) 27 { 28 void *ptr; 29 30 if (size == 0) 31 errx(2, NULL); 32 ptr = malloc(size); 33 if (ptr == NULL) 34 errx(2, NULL); 35 return ptr; 36 } 37 38 void * 39 xrealloc(void *ptr, size_t nmemb, size_t size) 40 { 41 void *new_ptr; 42 size_t new_size = nmemb * size; 43 44 if (new_size == 0) 45 errx(2, NULL); 46 if (SIZE_T_MAX / nmemb < size) 47 errx(2, NULL); 48 if (ptr == NULL) 49 new_ptr = malloc(new_size); 50 else 51 new_ptr = realloc(ptr, new_size); 52 if (new_ptr == NULL) 53 errx(2, NULL); 54 return new_ptr; 55 } 56 57 void 58 xfree(void *ptr) 59 { 60 if (ptr == NULL) 61 errx(2, NULL); 62 free(ptr); 63 } 64 65 char * 66 xstrdup(const char *str) 67 { 68 size_t len; 69 char *cp; 70 71 len = strlen(str) + 1; 72 cp = xmalloc(len); 73 strlcpy(cp, str, len); 74 return cp; 75 } 76 77 int 78 xasprintf(char **ret, const char *fmt, ...) 79 { 80 va_list ap; 81 int i; 82 83 va_start(ap, fmt); 84 i = vasprintf(ret, fmt, ap); 85 va_end(ap); 86 87 if (i < 0 || *ret == NULL) 88 errx(2, NULL); 89 90 return (i); 91 } 92