]> git.sur5r.net Git - i3/i3/blob - libi3/safewrappers.c
cf634ad43b8d0f9248f60f351f506908b3507d59
[i3/i3] / libi3 / safewrappers.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include <string.h>
9 #include <stdlib.h>
10 #include <stdarg.h>
11 #include <stdio.h>
12 #include <err.h>
13
14 #include "libi3.h"
15
16 /*
17  * The s* functions (safe) are wrappers around malloc, strdup, …, which exits if one of
18  * the called functions returns NULL, meaning that there is no more memory available
19  *
20  */
21 void *smalloc(size_t size) {
22     void *result = malloc(size);
23     if (result == NULL)
24         err(EXIT_FAILURE, "malloc(%zd)", size);
25     return result;
26 }
27
28 void *scalloc(size_t size) {
29     void *result = calloc(size, 1);
30     if (result == NULL)
31         err(EXIT_FAILURE, "calloc(%zd)", size);
32     return result;
33 }
34
35 void *srealloc(void *ptr, size_t size) {
36     void *result = realloc(ptr, size);
37     if (result == NULL && size > 0)
38         err(EXIT_FAILURE, "realloc(%zd)", size);
39     return result;
40 }
41
42 char *sstrdup(const char *str) {
43     char *result = strdup(str);
44     if (result == NULL)
45         err(EXIT_FAILURE, "strdup()");
46     return result;
47 }
48
49 int sasprintf(char **strp, const char *fmt, ...) {
50     va_list args;
51     int result;
52
53     va_start(args, fmt);
54     if ((result = vasprintf(strp, fmt, args)) == -1)
55         err(EXIT_FAILURE, "asprintf(%s)", fmt);
56     va_end(args);
57     return result;
58 }