From dba748f59345d1183898a8f94d0d3d184d4956f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89rico=20Rolim?= Date: Thu, 7 Jan 2021 18:23:36 -0300 Subject: [PATCH] Add xmalloc and xrealloc wrappers. --- string-array.c | 9 +++------ util.c | 17 +++++++++++++++++ util.h | 2 ++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/string-array.c b/string-array.c index c368f3f..199f20b 100644 --- a/string-array.c +++ b/string-array.c @@ -3,18 +3,15 @@ #include #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; diff --git a/util.c b/util.c index 6320fd6..5c0687f 100644 --- a/util.c +++ b/util.c @@ -1,3 +1,6 @@ +#include +#include + #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); +} diff --git a/util.h b/util.h index 33aeaa2..3941594 100644 --- a/util.h +++ b/util.h @@ -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