1360405Skevans/* $OpenBSD: xmalloc.c,v 1.10 2019/06/28 05:44:09 deraadt Exp $ */ 2315051Sbapt/* 3315051Sbapt * Author: Tatu Ylonen <ylo@cs.hut.fi> 4315051Sbapt * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 5315051Sbapt * All rights reserved 6315051Sbapt * Versions of malloc and friends that check their results, and never return 7315051Sbapt * failure (they call fatal if they encounter an error). 8315051Sbapt * 9315051Sbapt * As far as I am concerned, the code I have written for this software 10315051Sbapt * can be used freely for any purpose. Any derived versions of this 11315051Sbapt * software must be clearly marked as such, and if the derived work is 12315051Sbapt * incompatible with the protocol description in the RFC file, it must be 13315051Sbapt * called by a name other than "ssh" or "Secure Shell". 14315051Sbapt */ 15315051Sbapt 16315051Sbapt#include <sys/cdefs.h> 17315051Sbapt__FBSDID("$FreeBSD: stable/11/usr.bin/diff/xmalloc.c 360405 2020-04-27 22:34:45Z kevans $"); 18315051Sbapt 19315051Sbapt#include <err.h> 20315051Sbapt#include <stdarg.h> 21315051Sbapt#include <stdint.h> 22315051Sbapt#include <stdio.h> 23315051Sbapt#include <stdlib.h> 24315051Sbapt#include <string.h> 25315051Sbapt 26315051Sbapt#include "xmalloc.h" 27315051Sbapt 28315051Sbaptvoid * 29315051Sbaptxmalloc(size_t size) 30315051Sbapt{ 31315051Sbapt void *ptr; 32315051Sbapt 33315051Sbapt if (size == 0) 34315051Sbapt errx(2, "xmalloc: zero size"); 35315051Sbapt ptr = malloc(size); 36315051Sbapt if (ptr == NULL) 37315051Sbapt err(2, "xmalloc: allocating %zu bytes", size); 38315051Sbapt return ptr; 39315051Sbapt} 40315051Sbapt 41315051Sbaptvoid * 42315051Sbaptxcalloc(size_t nmemb, size_t size) 43315051Sbapt{ 44315051Sbapt void *ptr; 45315051Sbapt 46315051Sbapt ptr = calloc(nmemb, size); 47315051Sbapt if (ptr == NULL) 48315051Sbapt err(2, "xcalloc: allocating %zu * %zu bytes", nmemb, size); 49315051Sbapt return ptr; 50315051Sbapt} 51315051Sbapt 52315051Sbaptvoid * 53315051Sbaptxreallocarray(void *ptr, size_t nmemb, size_t size) 54315051Sbapt{ 55315051Sbapt void *new_ptr; 56315051Sbapt 57315051Sbapt new_ptr = reallocarray(ptr, nmemb, size); 58315051Sbapt if (new_ptr == NULL) 59315051Sbapt err(2, "xreallocarray: allocating %zu * %zu bytes", 60315051Sbapt nmemb, size); 61315051Sbapt return new_ptr; 62315051Sbapt} 63315051Sbapt 64315051Sbaptchar * 65315051Sbaptxstrdup(const char *str) 66315051Sbapt{ 67315051Sbapt char *cp; 68315051Sbapt 69315051Sbapt if ((cp = strdup(str)) == NULL) 70315051Sbapt err(2, "xstrdup"); 71315051Sbapt return cp; 72315051Sbapt} 73315051Sbapt 74315051Sbaptint 75315051Sbaptxasprintf(char **ret, const char *fmt, ...) 76315051Sbapt{ 77315051Sbapt va_list ap; 78315051Sbapt int i; 79315051Sbapt 80315051Sbapt va_start(ap, fmt); 81315051Sbapt i = vasprintf(ret, fmt, ap); 82315051Sbapt va_end(ap); 83315051Sbapt 84360405Skevans if (i == -1) 85315051Sbapt err(2, "xasprintf"); 86315051Sbapt 87315051Sbapt return i; 88315051Sbapt} 89