/*
 * nbmalloc.c  -  Memory allocation handling
 *
 * Copyright (C) 1998-2007 Gero Kuhlmann <gero@gkminix.han.de>
 *
 *  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 2 of the License, or
 *  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.
 *
 * $Id: nbmalloc.c,v 1.8 2007/01/06 18:31:38 gkminix Exp $
 */

#include <common.h>
#include <nblib.h>



/*
 * Check on the definition of malloc() and friends. Note that with
 * STDC_HEADERS defined, the malloc() routines should have been defined
 * in stdlib.h already (which gets included by common.h).
 */
#ifndef STDC_HEADERS
# ifdef HAVE_MALLOC_H
#  include <malloc.h>
# else
extern voidstar malloc();
extern voidstar realloc();
extern void free();
# endif
#endif



/*
 * Check memory allocation error
 */
static voidstar checkalloc __F((ptr), voidstar ptr)
{
  if (ptr == NULL) {
	prnerr("not enough memory");
	nbexit(EXIT_MEMORY);
  }
  return(ptr);
}



/*
 * Allocate memory - with error handling
 */
voidstar nbmalloc __F((amount), size_t amount)
{
  voidstar ptr;

  if (amount == 0)
	amount = 1;
  ptr = checkalloc(malloc(amount));
  memzero(ptr, amount);
  return(ptr);
}



/*
 * Allocate memory for nelem elements, each of size elsize
 */
voidstar nbcalloc __F((nelem, elsize), size_t nelem AND size_t elsize)
{
  size_t amount;

  if (nelem == 0)
	nelem = 1;
  if (elsize == 0)
	elsize = 1;
  amount = nelem * elsize;
  return(nbmalloc(amount));
}



/*
 * Reallocate an old memory block
 */
voidstar nbrealloc __F((oldmem, amount), voidstar oldmem AND size_t amount)
{
  voidstar ptr;

  /* Check if oldmem defined */
  if (oldmem == NULL)
	return(nbmalloc(amount));

  /* Reallocate oldmem */
  if (amount == 0)
	amount = 1;
  ptr = checkalloc(realloc(oldmem, amount));
  return(ptr);
}



/*
 * Copy a string into a newly allocated memory block
 */
void copystr __F((dest, src), char **dest AND const char *src)
{
  if (*dest != NULL)
	free(*dest);

  if (src == NULL) {
	*dest = NULL;
	return;
  }

  *dest = (char *)nbmalloc(strlen(src) + 1);
  strcpy(*dest, src);
}

