/*
    mmorph, MULTEXT morphology tool
    Version 2.3, October 1995
    Copyright (c) 1994,1995 ISSCO/SUISSETRA, Geneva, Switzerland
    Dominique Petitpierre, <petitp@divsun.unige.ch>
*/
/*
    mymalloc.c

    convenient wrappers around memory allocation functions
*/

#ifndef  MALLOC_FUNC_CHECK
#include <malloc.h>
#include <errno.h>
#include "mymalloc.h"
extern int  sys_nerr;
extern char *sys_errlist[];

/* extern char *strdup();*/

extern void fatal_error();

#define MEM_ERROR(f_name) \
	if (errno == ENOMEM) \
	    fatal_error("out of memory (%s)",f_name); \
	else \
	    fatal_error("program bug: memory allocation error (%s)",f_name)

void
my_malloc(var, size)
T_PTR      *var;
size_t      size;

{
    if ((*var = malloc(size)) == NULL)
	MEM_ERROR("malloc");
}

void
my_realloc(var, size)
T_PTR      *var;
size_t      size;

{
    if ((*var = realloc(*var, size)) == NULL)
	MEM_ERROR("realloc");
}


void
my_calloc(var, nelem, size)
T_PTR      *var;
size_t      nelem;
size_t      size;

{
    if ((*var = calloc(nelem, size)) == NULL)
	MEM_ERROR("calloc");
}

void
my_strdup(var, str)
char      **var;
char       *str;

{
    if ((*var = strdup(str)) == NULL)
	MEM_ERROR("strdup");
}

void
my_free(ptr)
T_PTR       ptr;

{
    if (ptr == NULL)
	fatal_error("program bug: trying to free a NULL pointer");
    errno = 0;	/* clear error */
#if defined(STDC_HEADERS) || defined(__GNUC__) || lint
    free(ptr);
    if (errno != 0)
	fatal_error("program bug: cannot free pointer (errno=%d=%s)",
		    errno, (errno < sys_nerr ? sys_errlist[errno] : "?"));
#else
    if (free(ptr) != 1)
	fatal_error("program bug: cannot free pointer (errno=%d)",
		    errno, (errno < sys_nerr ? sys_errlist[errno] : "?"));
#endif
}

#endif	/* MALLOC_FUNC_CHECK */
