Annotation of src/usr.bin/rcs/xmalloc.c, Revision 1.2
1.2 ! ray 1: /* $OpenBSD: xmalloc.c,v 1.1 2006/04/26 02:55:13 joris 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:
16: #include "includes.h"
17:
18: #include "xmalloc.h"
19:
20: void *
21: xmalloc(size_t size)
22: {
23: void *ptr;
24:
25: if (size == 0)
26: errx(1, "xmalloc: zero size");
27: ptr = malloc(size);
28: if (ptr == NULL)
29: errx(1,
30: "xmalloc: out of memory (allocating %lu bytes)",
31: (u_long) size);
32: return ptr;
33: }
34:
35: void *
36: xcalloc(size_t nmemb, size_t size)
37: {
38: void *ptr;
39:
40: if (size == 0 || nmemb == 0)
41: errx(1, "xcalloc: zero size");
42: if (SIZE_T_MAX / nmemb < size)
43: errx(1, "xcalloc: nmemb * size > SIZE_T_MAX");
44: ptr = calloc(nmemb, size);
45: if (ptr == NULL)
46: errx(1, "xcalloc: out of memory (allocating %lu bytes)",
47: (u_long)(size * nmemb));
48: return ptr;
49: }
50:
51: void *
52: xrealloc(void *ptr, size_t nmemb, size_t size)
53: {
54: void *new_ptr;
55: size_t new_size = nmemb * size;
56:
57: if (new_size == 0)
58: errx(1, "xrealloc: zero size");
59: if (SIZE_T_MAX / nmemb < size)
60: errx(1, "xrealloc: nmemb * size > SIZE_T_MAX");
61: if (ptr == NULL)
62: new_ptr = malloc(new_size);
63: else
64: new_ptr = realloc(ptr, new_size);
65: if (new_ptr == NULL)
66: errx(1, "xrealloc: out of memory (new_size %lu bytes)",
67: (u_long) new_size);
68: return new_ptr;
69: }
70:
71: void
72: xfree(void *ptr)
73: {
74: if (ptr == NULL)
75: errx(1, "xfree: NULL pointer given as argument");
76: free(ptr);
77: }
78:
79: char *
80: xstrdup(const char *str)
81: {
82: size_t len;
83: char *cp;
84:
85: len = strlen(str) + 1;
86: cp = xmalloc(len);
1.2 ! ray 87: if (strlcpy(cp, str, len) >= len)
! 88: errx(1, "xstrdup: string truncated");
1.1 joris 89: return cp;
90: }
91:
92: int
93: xasprintf(char **ret, const char *fmt, ...)
94: {
95: va_list ap;
96: int i;
97:
98: va_start(ap, fmt);
99: i = vasprintf(ret, fmt, ap);
100: va_end(ap);
101:
102: if (i < 0 || *ret == NULL)
103: errx(1, "xasprintf: could not allocate memory");
104:
105: return (i);
106: }