aboutsummaryrefslogtreecommitdiffstats
path: root/src/util.c
diff options
context:
space:
mode:
authorTharre <tharre3@gmail.com>2014-11-16 19:19:59 +0100
committerTharre <tharre3@gmail.com>2014-11-16 19:19:59 +0100
commitdf9bc5b9d048c7ecb96838123e39d5bc7c23aa18 (patch)
tree5432d5cc4a0e5a7550f7bae00964f09cb68b6361 /src/util.c
parentb4c1b2145d6a0b1ec4219847dc26877046f84e8b (diff)
downloadredo-df9bc5b9d048c7ecb96838123e39d5bc7c23aa18.tar.gz
redo-df9bc5b9d048c7ecb96838123e39d5bc7c23aa18.tar.xz
redo-df9bc5b9d048c7ecb96838123e39d5bc7c23aa18.zip
Refactor error handling system by using die()
Defined error messages have also been replaced with string literals.
Diffstat (limited to 'src/util.c')
-rw-r--r--src/util.c45
1 files changed, 29 insertions, 16 deletions
diff --git a/src/util.c b/src/util.c
index 797c84d..ce668fc 100644
--- a/src/util.c
+++ b/src/util.c
@@ -6,44 +6,57 @@
* of the MIT license. See the LICENSE file for details.
*/
+#define _XOPEN_SOURCE 500
+#include <assert.h>
+#include <errno.h>
#include <stdarg.h>
#include <stdint.h>
-#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
#include "util.h"
#define _FILENAME "util.c"
#include "dbg.h"
-void *safe_malloc_(size_t size, const char *file, unsigned line) {
+/* Print a given formated error message and die. */
+extern void __attribute__((noreturn)) die(const char *err, ...) {
+ assert(err);
+ va_list ap;
+ va_start(ap, err);
+
+ vfprintf(stderr, err, ap);
+
+ va_end(ap);
+ exit(EXIT_FAILURE);
+}
+
+void *xmalloc(size_t size) {
assert(size > 0);
void *ptr = malloc(size);
if (!ptr)
- fatal_(file, line, ERRM_MALLOC, size);
+ diem("Cannot allocate %zu bytes", size);
return ptr;
}
-void *safe_realloc_(void *ptr, size_t size, const char *file, unsigned line) {
+void *xrealloc(void *ptr, size_t size) {
assert(size > 0 && ptr);
- void *ptr2 = realloc(ptr, size);
- if (!ptr2)
- fatal_(file, line, ERRM_REALLOC, size);
+ if (!(ptr = realloc(ptr, size)))
+ diem("Cannot reallocate %zu bytes", size);
- return ptr2;
+ return ptr;
}
-char *safe_strdup_(const char *str, const char *file, unsigned line) {
+char *xstrdup(const char *str) {
assert(str);
- size_t len = strlen(str) + 1;
- char *ptr = malloc(len);
- if (!ptr)
- fatal_(file, line, ERRM_MALLOC, len);
+ if (!(str = strdup(str)))
+ diem("Insufficient memory for string allocation");
- return memcpy(ptr, str, len);
+ return (char*) str;
}
-
/* For concating multiple strings into a single larger one. */
char *concat(size_t count, ...) {
assert(count > 0);
@@ -56,7 +69,7 @@ char *concat(size_t count, ...) {
size += args_len[i];
}
++size;
- char *result = safe_malloc(size);
+ char *result = xmalloc(size);
/* debug("Allocated %zu bytes at %p\n", size, result); */
uintptr_t offset = 0;
for (i = 0; i < count; ++i) {