1/* $OpenBSD: xmalloc.c,v 1.31 2015/02/06 23:21:59 millert 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 "includes.h" 17 18#include <stdarg.h> 19#ifdef HAVE_STDINT_H 20#include <stdint.h> 21#endif 22#include <stdio.h> 23#include <stdlib.h> 24#include <string.h> 25 26#include "xmalloc.h" 27#include "log.h" 28 29void * 30xmalloc(size_t size) 31{ 32 void *ptr; 33 34 if (size == 0) 35 fatal("xmalloc: zero size"); 36 ptr = malloc(size); 37 if (ptr == NULL) 38 fatal("xmalloc: out of memory (allocating %zu bytes)", size); 39 return ptr; 40} 41 42void * 43xcalloc(size_t nmemb, size_t size) 44{ 45 void *ptr; 46 47 if (size == 0 || nmemb == 0) 48 fatal("xcalloc: zero size"); 49 if (SIZE_MAX / nmemb < size) 50 fatal("xcalloc: nmemb * size > SIZE_MAX"); 51 ptr = calloc(nmemb, size); 52 if (ptr == NULL) 53 fatal("xcalloc: out of memory (allocating %zu bytes)", 54 size * nmemb); 55 return ptr; 56} 57 58void * 59xrealloc(void *ptr, size_t nmemb, size_t size) 60{ 61 void *new_ptr; 62 size_t new_size = nmemb * size; 63 64 if (new_size == 0) 65 fatal("xrealloc: zero size"); 66 if (SIZE_MAX / nmemb < size) 67 fatal("xrealloc: nmemb * size > SIZE_MAX"); 68 if (ptr == NULL) 69 new_ptr = malloc(new_size); 70 else 71 new_ptr = realloc(ptr, new_size); 72 if (new_ptr == NULL) 73 fatal("xrealloc: out of memory (new_size %zu bytes)", 74 new_size); 75 return new_ptr; 76} 77 78char * 79xstrdup(const char *str) 80{ 81 size_t len; 82 char *cp; 83 84 len = strlen(str) + 1; 85 cp = xmalloc(len); 86 strlcpy(cp, str, len); 87 return cp; 88} 89 90int 91xasprintf(char **ret, const char *fmt, ...) 92{ 93 va_list ap; 94 int i; 95 96 va_start(ap, fmt); 97 i = vasprintf(ret, fmt, ap); 98 va_end(ap); 99 100 if (i < 0 || *ret == NULL) 101 fatal("xasprintf: could not allocate memory"); 102 103 return (i); 104} 105