static char rcsid[] = "@(#)$Id: safemalloc.c,v 1.15 2006/04/09 07:37:05 hurtta Exp $";

/******************************************************************************
 *  The Elm (ME+) Mail System  -  $Revision: 1.15 $   $State: Exp $
 *
 *  Modified by: Kari Hurtta <hurtta+elm@posti.FMI.FI> 
 *                           (was hurtta+elm@ozone.FMI.FI)
 ******************************************************************************
 *  The Elm Mail System 
 *
 * 			Copyright (c) 1992 USENET Community Trust
 *****************************************************************************/

#include "headers.h"

/*
 * These routines perform dynamic memory allocation with error checking.
 * The "safe_malloc_fail_handler" vector points to a routine that is invoked
 * if memory allocation fails.  The default error handler displays a message
 * and aborts the program.
 */


DEBUG_VAR(Debug,__FILE__,"mem");

void dflt_safe_malloc_fail_handler(proc, len)
     char *proc;
     unsigned len;
{    
#if DEBUG
    panic_dprint("ERROR - out of memory [%s failed allocating %d bytes]\n",
		 proc, len);
#endif

    fprintf(stderr,
	    "error - out of memory [%s failed allocating %d bytes]\n",
	    proc, len);
    exit(1);
}

void (*safe_malloc_fail_handler) P_((char *proc,
				     unsigned len)) = dflt_safe_malloc_fail_handler;

malloc_t safe_malloc(len)
     unsigned len;
{
	malloc_t p;
	if ((p = malloc(len)) == NULL) {
	    DPRINT(Debug,1,(&Debug,
			    "safe_malloc(%d)    FAILED\n",len));
	    (*safe_malloc_fail_handler)("safe_malloc", len);
	}
	DPRINT(Debug,100,(&Debug,
			  "safe_malloc(%d)=%p\n",len,p));
	return p;
}


malloc_t safe_realloc(p, len)
     malloc_t p;
     unsigned len;
{
        malloc_t po=p;
	if ((p = (p == NULL ? malloc(len) : realloc((malloc_t)p, len))) 
           == NULL) {
	    DPRINT(Debug,1,(&Debug,
			    "safe_realloc(%p,%d)     FAILED\n",po,len));
	    (*safe_malloc_fail_handler)("safe_realloc", len);
	}
	DPRINT(Debug,100,(&Debug,
			  "safe_realloc(%p,%d)=%p\n",po,len,p));
	return p;
}

char *safe_strdup(s)
     CONST char *s;
{
	char *p;
	int Len = strlen(s)+1;
	if ((p = (char *) malloc(Len)) == NULL) {
	    DPRINT(Debug,1,(&Debug,
			    "safe_strdup(%s)      FAILED\n",s));
	    (*safe_malloc_fail_handler)("safe_strdup", Len);
	}
	DPRINT(Debug,100,(&Debug,
			  "safe_strdup(%s)=%p\n",s,p));
	return strfcpy(p, s, Len);
}

#ifdef DEBUG
#undef free
void safe_free(x)
     malloc_t x;
{
    DPRINT(Debug,100,(&Debug,
		"(safe)free(%p) ",x));


    if (x == NULL) {
	DPRINT(Debug,1,(&Debug,
			"** FREE OF NULL POINTER\n"));
    }

    free(x);
    DPRINT(Debug,100,(&Debug,
		      "\n"));
}
#endif

/*
 * Local Variables:
 *  mode:c
 *  c-basic-offset:4
 *  buffer-file-coding-system: iso-8859-1
 * End:
 */


syntax highlighted by Code2HTML, v. 0.9.1