From ef852b1eb421ecf6f98efeee71f87c8fc4110c50 Mon Sep 17 00:00:00 2001 From: Lieuwe Rooijakkers Date: Sun, 21 Jul 2024 17:19:15 +0200 Subject: tak: betere foutafwerking --- src/tak.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/tak.c b/src/tak.c index 3aa4d84..bf8bfef 100644 --- a/src/tak.c +++ b/src/tak.c @@ -67,16 +67,26 @@ static void process(struct state state) { } } +#define CHECK_OOM(ptr) \ + if (ptr == NULL) { \ + fprintf(stderr, "tak: geheugen is op"); \ + /* I think I should free the original memory here, but whatever */ \ + return NULL; \ + } + static char *read_stdin(size_t *sz) { const size_t CHUNK_SIZE = 4096; + *sz = 0; size_t cap = CHUNK_SIZE; char *res = malloc(cap); + CHECK_OOM(res); while (!feof(stdin)) { if (cap-*sz < CHUNK_SIZE) { cap *= 2; res = realloc(res, cap); + CHECK_OOM(res); } const size_t n = fread(res+*sz, 1, CHUNK_SIZE, stdin); @@ -84,7 +94,8 @@ static char *read_stdin(size_t *sz) { if (n != CHUNK_SIZE && !feof(stdin)) { fprintf(stderr, "tak: fout tijdens lezen van standaard invoer.\n"); - exit(1); + free(res); + return NULL; } } @@ -96,6 +107,9 @@ int entry_tak(int argc, char **argv) { if (*args == NULL) { size_t sz = 0; char *data = read_stdin(&sz); + if (data == NULL) { + return 1; + } struct state state = { .buf = data, .sz = sz }; process(state); -- cgit v1.2.3-70-g09d2