/*
 * alloc.c - memory allocation
 *
 * Copyright (C) 1999, 2000 Martin Grabmueller <mgrabmue@cs.tu-berlin.de>
 *
 * This 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, or (at your option)
 * any later version.
 * 
 * This software 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 package; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.  
 */

#include <stdlib.h>
#include <stdio.h>

#include "alloc.h"

/*
 * Count the amount of allocated memory in bytes.
 */
unsigned allocated_bytes = 0;

/*
 * Allocate SIZE bytes, abort the program if there is no memory
 * left.  Returns a pointer to the allocated memory.
 */
void * 
xmalloc (unsigned size)
{
  void * ptr;

  if ((ptr = (void *) malloc(size)))
    allocated_bytes += size;
  else
    {
      fprintf(stderr, "fatal: virtual memory exhausted\n");
      exit(1);
    }

  return ptr;
}

/*
 * Change the size of the xmalloc()'ed block of memory pointed to by
 * PTR.  Abort the program if there is no memory left.  The new size
 * of the block is passed in SIZE, the old size in OLD_SIZE.  The last
 * parameter is needed to track memory usage.
 */
void *
xrealloc (void * ptr, unsigned size, unsigned old_size)
{
  if (ptr)
    {
      if ((ptr = (void *) realloc(ptr, size)))
	allocated_bytes += size - old_size;
      else
	{
	  fprintf(stderr, "fatal: virtual memory exhausted\n");
	  exit(1);
	}
    }
  else
    ptr = xmalloc(size);

  return ptr;
}

/*
 * Free the block of xmalloc()'ed or xrealloc()'ed memory pointed to
 * by PTR.  SIZE is the size of the block to be freed and is used to
 * track memory usage.
 */
void
xfree (void * ptr, unsigned size)
{
  free(ptr);
  allocated_bytes -= size;
}

