summaryrefslogtreecommitdiffstats
path: root/util.c
blob: 07ebfc0ea341efb6a8da4fe3e52ffc4f9b006281 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* See LICENSE file for copyright and license details. */
#include "common.h"


void *
erealloc(void *ptr, size_t n)
{
	void *ret = realloc(ptr, n);
	if (!ret)
		eprintf("realloc %zu:", n);
	return ret;
}


void *
ecalloc(size_t n, size_t m)
{
	void *ret = calloc(n, m);
	if (!ret)
		eprintf("calloc %zu %zu:", n, m);
	return ret;
}


void *
emalloc(size_t n)
{
	void *ret = malloc(n);
	if (!ret)
		eprintf("malloc %zu:", n);
	return ret;
}


void *
ememdup(const void *ptr, size_t n)
{
	void *ret = emalloc(n);
	memcpy(ret, ptr, n);
	return ret;
}


void
eprintf(const char *fmt, ...)
{
	va_list ap;
	int err = errno;
	char end = *fmt ? strchr(fmt, '\0')[-1] : '\0';
	va_start(ap, fmt);
	fprintf(stderr, "%s: ", argv0);
	vfprintf(stderr, fmt, ap);
	if (end == '\0')
		fprintf(stderr, "%s\n", strerror(err));
	else if (end == ':')
		fprintf(stderr, " %s\n", strerror(err));
	else if (end != '\n')
		fprintf(stderr, "\n");
	va_end(ap);
	exit(EXIT_ERROR);
}