From c65669a785fba9b1f0f7539f47a677035ea06229 Mon Sep 17 00:00:00 2001 From: pacien Date: Sat, 2 Dec 2017 01:07:20 +0100 Subject: Add some common utility functions Signed-off-by: pacien --- include/common/error.h | 24 ++++++++++++++++++++++++ include/common/mem.h | 23 +++++++++++++++++++++++ src/common/error.c | 8 ++++++++ src/common/mem.c | 12 ++++++++++++ 4 files changed, 67 insertions(+) create mode 100644 include/common/error.h create mode 100644 include/common/mem.h create mode 100644 src/common/error.c create mode 100644 src/common/mem.c diff --git a/include/common/error.h b/include/common/error.h new file mode 100644 index 0000000..522d646 --- /dev/null +++ b/include/common/error.h @@ -0,0 +1,24 @@ +#ifndef UPEM_MORPHING_ERROR +#define UPEM_MORPHING_ERROR + +/** + * File: error.h + */ + +/** + * Constants: Common errors + * + * OUT_OF_MEMORY_ERROR - when memory cannot be allocated for the program + */ +#define OUT_OF_MEMORY_ERROR "Out of memory" + +/** + * Function: rage quit + * Logs the supplied error message to stderr before exiting the program with an error status code. + * + * Parameters; + * *msg - error message to log + */ +void rage_quit(const char *msg); + +#endif diff --git a/include/common/mem.h b/include/common/mem.h new file mode 100644 index 0000000..1c46778 --- /dev/null +++ b/include/common/mem.h @@ -0,0 +1,23 @@ +#ifndef UPEM_MORPHING_MEM +#define UPEM_MORPHING_MEM + +/** + * File: mem.h + */ + +#include + +/** + * Function: malloc_or_die + * Allocates a memory chunk of the requested size. + * Interrupts the execution of the program in case of an error. + * + * Parameters: + * size - size of the chunk to allocate + * + * Returns: + * A non-NULL pointer to the allocated chunk + */ +void *malloc_or_die(size_t size); + +#endif diff --git a/src/common/error.c b/src/common/error.c new file mode 100644 index 0000000..f28a6cd --- /dev/null +++ b/src/common/error.c @@ -0,0 +1,8 @@ +#include "common/error.h" +#include +#include + +void rage_quit(const char *msg) { + fprintf(stderr, "FATAL ERROR: %s\n", msg); + exit(1); +} diff --git a/src/common/mem.c b/src/common/mem.c new file mode 100644 index 0000000..855e010 --- /dev/null +++ b/src/common/mem.c @@ -0,0 +1,12 @@ +#include "common/mem.h" +#include +#include "common/error.h" + +void *malloc_or_die(size_t size) { + void *ptr = malloc(size); + + if (ptr == NULL) + rage_quit(OUT_OF_MEMORY_ERROR); + + return ptr; +} -- cgit v1.2.3