/* $Id: xmalloc 3.2.0.2 1998/07/26 10:55:08 stoklund Exp stoklund $ */
/* xmalloc.c: malloc with error checking.

   Copyright (C) 1992, 93 Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

#include <stdio.h>
#include "kpathsea:config.h"

#ifdef KPSE_MEM_DEBUG
FILE *mlogfile = NULL;
void *
_xmalloc P3C (unsigned, size, const_string, file, int, line)
#else
void *
xmalloc P1C (unsigned, size)
#endif
{
  void *new_mem = (void *) malloc (size);

  if (new_mem == NULL)
    {
      fprintf (stderr, "fatal: memory exhausted (xmalloc of %u bytes).\n",
	       size);
#ifdef KPSE_MEM_DEBUG
      if (file)
	fprintf (stderr, "%s, line %d.\n", file, line);
#endif
      exit (EXIT_FAILURE);
    }

#ifdef KPSE_MEM_DEBUG
  if (!mlogfile)
    mlogfile = fopen ("mallog", "w");
  fprintf (mlogfile, "%s: %d: malloc(%d) => %p\n", file, line, size, new_mem);
#endif

  return new_mem;
}


#ifdef KPSE_MEM_DEBUG
#undef free /* avoid recursion */

void
_free (address ptr, const_string file, int line)
{
  free (ptr);
  fprintf (mlogfile, "%s: %d: free(%p)\n", file, line, ptr);
}
#endif
