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

#include "config.h"

#ifndef NULL
#define NULL    0L
#endif

#ifdef __STDC__
#define T_PTR	void *
#else
#define T_PTR	char *
#endif

#ifdef  MALLOC_FUNC_CHECK

#include <malloc.h>

#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)

#define	my_malloc(var, size) \
{ \
    if ((*(var) = malloc(size)) == NULL) \
	MEM_ERROR("malloc"); \
}

#define my_realloc(var, size) \
{ \
    if ((*(var) = realloc(*(var), (size))) == NULL) \
	MEM_ERROR("realloc"); \
}


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

#define my_strdup(var, str) \
{ \
    if ((*(var) = STRDUP(str)) == NULL) \
	MEM_ERROR("strdup"); \
}

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

#endif	/* defined(STDC_HEADERS) || defined(__GNUC__) || lint */
#else

extern void my_malloc();
extern void my_free();
extern void my_realloc();
extern void my_calloc();
extern void my_strdup();

#endif	/* MALLOC_FUNC_CHECK */

#define MY_MALLOC(var,type) \
    my_malloc((T_PTR *) &(var), (size_t) sizeof (type))

#define MY_STRALLOC(var,size) \
    my_malloc((T_PTR *) &(var), (size_t) size)

#define MY_REALLOC(var, nelem, type) \
    my_realloc((T_PTR *) &(var), (size_t) ((nelem) * sizeof (type)))

#define MY_CALLOC(var,nelem,type) \
    my_calloc((T_PTR *) &(var), (size_t) (nelem), (size_t) sizeof (type))

#define MY_STRDUP(var,str) \
    my_strdup((char **) &(var), (char *) (str))

#define MY_FREE(ptr) \
    my_free((T_PTR) (ptr))



#endif	/* mymalloc_h */
