Add xmalloc and xrealloc wrappers.

This commit is contained in:
Érico Rolim 2021-01-07 18:23:36 -03:00
parent ef21f16b54
commit dba748f593
3 changed files with 22 additions and 6 deletions

View File

@ -3,18 +3,15 @@
#include <stdio.h>
#include "string-array.h"
#include "util.h"
void add_entry(struct str_array *a, char *s)
{
if (a->n == a->c) {
if (a->c == 0) a->c = 32;
else a->c *= 2;
a->v = realloc(a->v, sizeof(*a->v) * a->c);
a->m = realloc(a->m, sizeof(*a->m) * a->c);
if (!a->v || !a->m) {
perror("realloc");
exit(1);
}
a->v = xrealloc(a->v, sizeof(*a->v) * a->c);
a->m = xrealloc(a->m, sizeof(*a->m) * a->c);
}
a->v[a->n] = s;

17
util.c
View File

@ -1,3 +1,6 @@
#include <stdlib.h>
#include <unistd.h>
#include "util.h"
void read_entries_from_stream(struct str_array *a, int delim, FILE *input)
@ -13,3 +16,17 @@ void read_entries_from_stream(struct str_array *a, int delim, FILE *input)
tmp = 0;
}
}
void *xmalloc(size_t s) {
void *r = malloc(s);
if (r) return r;
perror("malloc");
exit(1);
}
void *xrealloc(void *p, size_t s) {
void *r = realloc(p, s);
if (r) return r;
perror("realloc");
exit(1);
}

2
util.h
View File

@ -6,5 +6,7 @@
#include "string-array.h"
void read_entries_from_stream(struct str_array *, int, FILE *);
void *xmalloc(size_t);
void *xrealloc(void *, size_t);
#endif