Xinqi Bao's Git

initial import
[dmenu.git] / util.c
1 /*
2 * (C)opyright MMVI Anselm R. Garbe <garbeam at gmail dot com>
3 * See LICENSE file for license details.
4 */
5 #include "dmenu.h"
6 #include <stdarg.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/wait.h>
11 #include <unistd.h>
12
13 /* static */
14
15 static void
16 bad_malloc(unsigned int size)
17 {
18 eprint("fatal: could not malloc() %u bytes\n", size);
19 }
20
21 /* extern */
22
23 void *
24 emalloc(unsigned int size)
25 {
26 void *res = malloc(size);
27 if(!res)
28 bad_malloc(size);
29 return res;
30 }
31
32 void *
33 emallocz(unsigned int size)
34 {
35 void *res = calloc(1, size);
36
37 if(!res)
38 bad_malloc(size);
39 return res;
40 }
41
42 void
43 eprint(const char *errstr, ...)
44 {
45 va_list ap;
46
47 va_start(ap, errstr);
48 vfprintf(stderr, errstr, ap);
49 va_end(ap);
50 exit(EXIT_FAILURE);
51 }
52
53 char *
54 estrdup(const char *str)
55 {
56 void *res = strdup(str);
57 if(!res)
58 bad_malloc(strlen(str));
59 return res;
60 }
61
62 void
63 swap(void **p1, void **p2)
64 {
65 void *tmp = *p1;
66 *p1 = *p2;
67 *p2 = tmp;
68 }