Skip to content

Commit

Permalink
Add xmalloc.h
Browse files Browse the repository at this point in the history
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
  • Loading branch information
donald committed Apr 15, 2020
1 parent 526b09e commit e629d62
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions xmalloc.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#ifndef _XMALLOC_H
#define _XMALLOC_H 1

#include <stdio.h>
#include <stdlib.h>

__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

0 comments on commit e629d62

Please sign in to comment.