-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathxmem.c
63 lines (60 loc) · 1.4 KB
/
xmem.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
// Copyright (c) 2009 David Caldwell, All Rights Reserved.
#define _GNU_SOURCE
#include <string.h>
#include <errno.h>
#include <err.h>
#include "xmem.h"
void *xmalloc(size_t size)
{
void *mem = malloc(size);
if (!mem) err(errno, "Out of memory");
return mem;
}
void *xcalloc(size_t count, size_t size)
{
void *mem = calloc(count, size);
if (!mem) err(errno, "Out of memory");
return mem;
}
void *xrealloc(void *old, size_t count)
{
void *mem = realloc(old, count);
if (!mem) err(errno, "Out of memory");
return mem;
}
char *xstrdup(char *s)
{
char *dup = strdup(s);
if (!dup) err(errno, "Out of memory");
return dup;
}
void *xmemdup(void *mem, size_t size)
{
void *dup = xmalloc(size);
memcpy(dup, mem, size);
return dup;
}
// Like strcat, but reallocs to make room (so dest must come from malloc)
char *xstrcat(char *dest, char *src)
{
if (!dest) return xstrdup(src);
dest = xrealloc(dest, strlen(dest) + strlen(src) + 1);
strcat(dest, src);
return dest;
}
#include <stdarg.h>
#include <stdio.h>
int vxsprintf(char **out, const char *format, va_list ap)
{
int count = vasprintf(out, format, ap);
if (count == -1 || !*out) err(errno, "Out of memory");
return count;
}
int xsprintf(char **out, char *format, ...)
{
va_list ap;
va_start(ap, format);
int count = vxsprintf(out, format, ap);
va_end(ap);
return count;
}