
#ifndef ALLOC_H
#define ALLOC_H

#define ALLOC_H_ENOMEM_MSG "insufficient heap memory is available"

/* This header provides error-checking interfaces to malloc(3)
 * and calloc(3), per Giacomo Catenazzi's Dec 2003 suggestion.
 * The malloc2() and calloc2() inlines defined here either
 *
 *   + succeed or
 *
 *   + abort the program.
 *
 * They never return null.
 *
 */

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <error.h>

static inline void *malloc2( const size_t size ) {
  void *const p = malloc( size );
  if (!p) error( ENOMEM, 0, ALLOC_H_ENOMEM_MSG );
  return p;
}

static inline void *calloc2( const size_t nmemb, const size_t size ) {
  void *const p = calloc( nmemb, size );
  if (!p) error( ENOMEM, 0, ALLOC_H_ENOMEM_MSG );
  return p;
}

static inline void *strdup2( const char *s ) {
  char *const p = strdup( s );
  if (!p) error( ENOMEM, 0, ALLOC_H_ENOMEM_MSG );
  return p;
}

#endif

