-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.c
72 lines (52 loc) · 1.32 KB
/
util.c
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
62
63
64
65
66
67
68
69
70
71
72
/* xml2json
*
* Copyright (c) 2018 Partha Susarla <mail@spartha.org>
*/
#include "util.h"
void *xmalloc(size_t size)
{
void *ret;
ret = malloc(size);
if (!ret && !size)
ret = malloc(1);
if (!ret) {
fprintf(stderr, "Out of memory. malloc failed.\n");
exit(EXIT_FAILURE);
}
return ret;
}
void *xrealloc(void *ptr, size_t size)
{
void *ret;
ret = realloc(ptr, size);
if (!ret && !size)
ret = realloc(ptr, 1);
if (!ret) {
fprintf(stderr, "Out of memory. realloc failed.\n");
exit(EXIT_FAILURE);
}
return ret;
}
void *xcalloc(size_t nmemb, size_t size)
{
void *ret = NULL;
if (!nmemb || !size)
return ret;
if (((size_t) - 1) / nmemb <= size) {
fprintf(stderr, "Memory allocation error\n");
exit(EXIT_FAILURE);
}
ret = (void *)calloc(nmemb, size);
if (!ret) {
fprintf(stderr, "Memory allocation error\n");
exit(EXIT_FAILURE);
}
return ret;
}
char *xstrdup(const char *s)
{
size_t len = strlen(s) + 1;
char *ptr = xmalloc(len);
memcpy(ptr, s, len);
return ptr;
}