Home | History | Annotate | Line # | Download | only in diff
      1 /* $OpenBSD: xmalloc.c,v 1.10 2019/06/28 05:44:09 deraadt Exp $ */
      2 /*
      3  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      4  * Copyright (c) 1995 Tatu Ylonen <ylo (at) 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 <sys/cdefs.h>
     17 #include <err.h>
     18 #include <stdarg.h>
     19 #include <stdint.h>
     20 #include <stdio.h>
     21 #include <stdlib.h>
     22 #include <string.h>
     23 
     24 #include "xmalloc.h"
     25 
     26 void *
     27 xmalloc(size_t size)
     28 {
     29 	void *ptr;
     30 
     31 	if (size == 0)
     32 		errx(2, "xmalloc: zero size");
     33 	ptr = malloc(size);
     34 	if (ptr == NULL)
     35 		err(2, "xmalloc: allocating %zu bytes", size);
     36 	return ptr;
     37 }
     38 
     39 void *
     40 xcalloc(size_t nmemb, size_t size)
     41 {
     42 	void *ptr;
     43 
     44 	ptr = calloc(nmemb, size);
     45 	if (ptr == NULL)
     46 		err(2, "xcalloc: allocating %zu * %zu bytes", nmemb, size);
     47 	return ptr;
     48 }
     49 
     50 void *
     51 xreallocarray(void *ptr, size_t nmemb, size_t size)
     52 {
     53 	void *new_ptr = ptr;
     54 
     55 	if (reallocarr(&new_ptr, nmemb, size) != 0) {
     56 		err(2, "xreallocarray: allocating %zu * %zu bytes",
     57 		    nmemb, size);
     58 	}
     59 	return new_ptr;
     60 }
     61 
     62 char *
     63 xstrdup(const char *str)
     64 {
     65 	char *cp;
     66 
     67 	if ((cp = strdup(str)) == NULL)
     68 		err(2, "xstrdup");
     69 	return cp;
     70 }
     71 
     72 int
     73 xasprintf(char **ret, const char *fmt, ...)
     74 {
     75 	va_list ap;
     76 	int i;
     77 
     78 	va_start(ap, fmt);
     79 	i = vasprintf(ret, fmt, ap);
     80 	va_end(ap);
     81 
     82 	if (i == -1)
     83 		err(2, "xasprintf");
     84 
     85 	return i;
     86 }
     87