Drop main() prototype. Syncs with NetBSD-8
[minix.git] / external / bsd / tmux / dist / xmalloc.c
blob236588cc5b8a5a2e131aa6c300a0169aa2db9ccf
1 /* Id */
3 /*
4 * Copyright (c) 2004 Nicholas Marriott <nicm@users.sourceforge.net>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/param.h>
21 #include <errno.h>
22 #include <libgen.h>
23 #include <stdlib.h>
24 #include <string.h>
26 #include "tmux.h"
28 char *
29 xstrdup(const char *s)
31 char *ptr;
32 size_t len;
34 len = strlen(s) + 1;
35 ptr = xmalloc(len);
37 strlcpy(ptr, s, len);
38 return (ptr);
41 void *
42 xcalloc(size_t nmemb, size_t size)
44 void *ptr;
46 if (size == 0 || nmemb == 0)
47 fatalx("zero size");
48 if (SIZE_MAX / nmemb < size)
49 fatalx("nmemb * size > SIZE_MAX");
50 if ((ptr = calloc(nmemb, size)) == NULL)
51 fatal("xcalloc failed");
53 return (ptr);
56 void *
57 xmalloc(size_t size)
59 void *ptr;
61 if (size == 0)
62 fatalx("zero size");
63 if ((ptr = malloc(size)) == NULL)
64 fatal("xmalloc failed");
66 return (ptr);
69 void *
70 xrealloc(void *oldptr, size_t nmemb, size_t size)
72 size_t newsize = nmemb * size;
73 void *newptr;
75 if (newsize == 0)
76 fatalx("zero size");
77 if (SIZE_MAX / nmemb < size)
78 fatalx("nmemb * size > SIZE_MAX");
79 if ((newptr = realloc(oldptr, newsize)) == NULL)
80 fatal("xrealloc failed");
82 return (newptr);
85 int printflike2
86 xasprintf(char **ret, const char *fmt, ...)
88 va_list ap;
89 int i;
91 va_start(ap, fmt);
92 i = xvasprintf(ret, fmt, ap);
93 va_end(ap);
95 return (i);
98 int
99 xvasprintf(char **ret, const char *fmt, va_list ap)
101 int i;
103 i = vasprintf(ret, fmt, ap);
104 if (i < 0 || *ret == NULL)
105 fatal("xvasprintf failed");
107 return (i);
110 int printflike3
111 xsnprintf(char *buf, size_t len, const char *fmt, ...)
113 va_list ap;
114 int i;
116 va_start(ap, fmt);
117 i = xvsnprintf(buf, len, fmt, ap);
118 va_end(ap);
120 return (i);
124 xvsnprintf(char *buf, size_t len, const char *fmt, va_list ap)
126 int i;
128 if (len > INT_MAX)
129 fatalx("len > INT_MAX");
131 i = vsnprintf(buf, len, fmt, ap);
132 if (i < 0)
133 fatal("vsnprintf failed");
135 return (i);