/*\
 *	DISTRIBUTION: HNMS v2.0
 *	FILE: hnmslib/alloc.c
 *
 *	Safe memory allocation routines for HNMS.
 *
 *	Jude George
 *	NAS Facility, NASA Ames Research Center
 *
 *	Copyright (c) 1994 Jude George
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation; either version 1, or (at your option)
 *	any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
\*/

#include <malloc.h>

#include "stdhnms.h"

/*\
 *  Safe memory allocation (calloc) for HNMS.
\*/
void *HNMS_alloc(nelem, size)
    const size_t	nelem;
    const size_t	size;
{
    static unsigned int	alloc_bytes = 0, alloc_calls = 0;
    void		*ptr;

    ptr = calloc(nelem, size);
    if (!ptr) {
	hnms_errno = HNMS_err_alloc;
	HNMS_debug(DEBUG_ERRORS, "HNMS_alloc");
	perror("calloc() failed!");
	abort();
    }
    alloc_calls++;
    alloc_bytes+= nelem * size;
    return ptr;
}

/*\
 *  Safe memory allocation (realloc) for HNMS.
\*/
void *HNMS_realloc(optr, size)
    void		*optr;
    const size_t	size;
{
    static unsigned int	realloc_bytes = 0, realloc_calls = 0;
    void		*ptr;

    if (!optr) {
	realloc_calls++;
	realloc_bytes+= size;
	return HNMS_alloc(1, size);
    }
    else {
	ptr = realloc(optr, size);
	if (!ptr) {
	    hnms_errno = HNMS_err_alloc;
	    HNMS_debug(DEBUG_ERRORS, "HNMS_realloc");
	    perror("realloc() failed!");
	    abort();
	}
	realloc_calls++;
	realloc_bytes+= size;
	return ptr;
    }
}
