Annotation of src/usr.bin/rcs/xmalloc.c, Revision 1.9
1.9 ! nicm 1: /* $OpenBSD: xmalloc.c,v 1.8 2015/03/26 15:17:30 okan Exp $ */
1.1 joris 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:
1.3 xsa 16: #include <err.h>
17: #include <stdarg.h>
1.7 millert 18: #include <stdint.h>
1.3 xsa 19: #include <stdio.h>
20: #include <stdlib.h>
21: #include <string.h>
1.1 joris 22:
23: #include "xmalloc.h"
24:
25: void *
26: xmalloc(size_t size)
27: {
28: void *ptr;
29:
30: if (size == 0)
31: errx(1, "xmalloc: zero size");
32: ptr = malloc(size);
33: if (ptr == NULL)
34: errx(1,
1.5 otto 35: "xmalloc: out of memory (allocating %zu bytes)",
36: size);
1.1 joris 37: return ptr;
38: }
39:
40: void *
41: xcalloc(size_t nmemb, size_t size)
42: {
43: void *ptr;
44:
45: if (size == 0 || nmemb == 0)
46: errx(1, "xcalloc: zero size");
1.4 ray 47: if (SIZE_MAX / nmemb < size)
48: errx(1, "xcalloc: nmemb * size > SIZE_MAX");
1.1 joris 49: ptr = calloc(nmemb, size);
50: if (ptr == NULL)
1.5 otto 51: errx(1, "xcalloc: out of memory (allocating %zu bytes)",
52: (size * nmemb));
1.1 joris 53: return ptr;
54: }
55:
56: void *
1.6 deraadt 57: xreallocarray(void *ptr, size_t nmemb, size_t size)
1.1 joris 58: {
59: void *new_ptr;
60:
1.6 deraadt 61: new_ptr = reallocarray(ptr, nmemb, size);
1.1 joris 62: if (new_ptr == NULL)
1.8 okan 63: errx(1, "xreallocarray: out of memory (new_size %zu bytes)",
1.6 deraadt 64: nmemb * size);
1.1 joris 65: return new_ptr;
66: }
67:
68: char *
69: xstrdup(const char *str)
70: {
71: size_t len;
72: char *cp;
73:
74: len = strlen(str) + 1;
75: cp = xmalloc(len);
1.2 ray 76: if (strlcpy(cp, str, len) >= len)
77: errx(1, "xstrdup: string truncated");
1.1 joris 78: return cp;
79: }
80:
81: int
82: xasprintf(char **ret, const char *fmt, ...)
83: {
84: va_list ap;
85: int i;
86:
87: va_start(ap, fmt);
88: i = vasprintf(ret, fmt, ap);
89: va_end(ap);
90:
91: if (i < 0 || *ret == NULL)
92: errx(1, "xasprintf: could not allocate memory");
93:
94: return (i);
95: }