From e629d62a387549cee7242d422028926f11ea47e7 Mon Sep 17 00:00:00 2001 From: Donald Buczek Date: Wed, 15 Apr 2020 15:25:02 +0200 Subject: [PATCH] Add xmalloc.h Add header file for the quasi-standard [1] xmalloc call. The current approach implemented in mx_util is to wait and retry on ENOMEM malloc failure. However, this overhead doesn't seem to be justified, because it is difficult to imagine a case, where a malloc would fail with ENOMEM at one time and a retry would succeed. [1] https://www.gnu.org/software/libc/manual/html_node/Malloc-Examples.html --- xmalloc.h | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 xmalloc.h diff --git a/xmalloc.h b/xmalloc.h new file mode 100644 index 00000000..23705bdd --- /dev/null +++ b/xmalloc.h @@ -0,0 +1,33 @@ +#ifndef _XMALLOC_H +#define _XMALLOC_H 1 + +#include +#include + +__attribute__ ((noreturn, unused)) static void out_of_memory() { + fprintf(stderr,"out of memory\n"); + abort(); +} + +__attribute__ ((unused)) static void *xmalloc(size_t size) { + void *ptr = malloc(size); + if (ptr == NULL) + out_of_memory(); + return(ptr); +} + +__attribute__ ((unused)) static void *xrealloc(void *ptr, size_t size) { + void *outptr = realloc(ptr, size); + if (outptr == NULL) + out_of_memory(); + return(outptr); +} + +__attribute__ ((unused)) static char *xstrndup(const char *s, size_t n) { + char *ptr = strndup(s, n); + if (ptr == NULL) + out_of_memory(); + return(ptr); +} + +#endif