-
Notifications
You must be signed in to change notification settings - Fork 0
/
mem.c
78 lines (61 loc) · 1.09 KB
/
mem.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
73
74
75
76
77
78
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include "mem.h"
void *umalloc(size_t l)
{
void *p = malloc(l);
if(!p)
abort();
memset(p, 0, l);
return p;
}
void *urealloc(void *p, size_t l)
{
void *r = realloc(p, l);
if(!r)
abort();
return r;
}
char *ustrdup(const char *s)
{
char *r = umalloc(strlen(s) + 1);
strcpy(r, s);
return r;
}
char *ustrdup_len(const char *s, size_t len)
{
char *r = umalloc(len + 1);
memcpy(r, s, len);
r[len] = '\0';
return r;
}
char *join(const char *sep, char **vec, int n)
{
const int len_sep = strlen(sep);
int len = 1;
for(int i = 0; i < n; i++)
len += len_sep + strlen(vec[i]);
char *p, *r = p = umalloc(len);
const char *sep_actual = "";
for(int i = 0; i < n; i++){
p += sprintf(p, "%s%s", sep_actual, vec[i]);
sep_actual = sep;
}
return r;
}
char *ustrvprintf(const char *fmt, va_list l)
{
char *buf = NULL;
int len = 8, ret;
do{
va_list lcp;
len *= 2;
buf = urealloc(buf, len);
va_copy(lcp, l);
ret = vsnprintf(buf, len, fmt, lcp);
va_end(lcp);
}while(ret >= len);
return buf;
}