Fix bind-key -t.
[tmux-openbsd.git] / xmalloc.c
blob43b0080dd0ac88f18cb528dd42609fb584193abc
1 /* $OpenBSD$ */
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 <stdint.h>
24 #include <stdlib.h>
25 #include <string.h>
27 #include "tmux.h"
29 char *
30 xstrdup(const char *s)
32 char *ptr;
33 size_t len;
35 len = strlen(s) + 1;
36 ptr = xmalloc(len);
38 strlcpy(ptr, s, len);
39 return (ptr);
42 void *
43 xcalloc(size_t nmemb, size_t size)
45 void *ptr;
47 if (size == 0 || nmemb == 0)
48 fatalx("zero size");
49 if (SIZE_MAX / nmemb < size)
50 fatalx("nmemb * size > SIZE_MAX");
51 if ((ptr = calloc(nmemb, size)) == NULL)
52 fatal("xcalloc failed");
54 return (ptr);
57 void *
58 xmalloc(size_t size)
60 void *ptr;
62 if (size == 0)
63 fatalx("zero size");
64 if ((ptr = malloc(size)) == NULL)
65 fatal("xmalloc failed");
67 return (ptr);
70 void *
71 xrealloc(void *oldptr, size_t nmemb, size_t size)
73 size_t newsize = nmemb * size;
74 void *newptr;
76 if (newsize == 0)
77 fatalx("zero size");
78 if (SIZE_MAX / nmemb < size)
79 fatalx("nmemb * size > SIZE_MAX");
80 if ((newptr = realloc(oldptr, newsize)) == NULL)
81 fatal("xrealloc failed");
83 return (newptr);
86 void
87 xfree(void *ptr)
89 if (ptr == NULL)
90 fatalx("null pointer");
91 free(ptr);
94 int printflike2
95 xasprintf(char **ret, const char *fmt, ...)
97 va_list ap;
98 int i;
100 va_start(ap, fmt);
101 i = xvasprintf(ret, fmt, ap);
102 va_end(ap);
104 return (i);
108 xvasprintf(char **ret, const char *fmt, va_list ap)
110 int i;
112 i = vasprintf(ret, fmt, ap);
113 if (i < 0 || *ret == NULL)
114 fatal("xvasprintf failed");
116 return (i);
119 int printflike3
120 xsnprintf(char *buf, size_t len, const char *fmt, ...)
122 va_list ap;
123 int i;
125 va_start(ap, fmt);
126 i = xvsnprintf(buf, len, fmt, ap);
127 va_end(ap);
129 return (i);
133 xvsnprintf(char *buf, size_t len, const char *fmt, va_list ap)
135 int i;
137 if (len > INT_MAX)
138 fatalx("len > INT_MAX");
140 i = vsnprintf(buf, len, fmt, ap);
141 if (i < 0)
142 fatal("vsnprintf failed");
144 return (i);