1/* alloc.c -- Default memory allocation routines.
2
3  (c) 1998-2005 (W3C) MIT, ERCIM, Keio University
4  See tidy.h for the copyright notice.
5
6  CVS Info :
7
8    $Author: iccir $
9    $Date: 2007/01/30 23:46:51 $
10    $Revision: 1.3 $
11
12*/
13
14#include "tidy.h"
15
16static TidyMalloc  g_malloc  = NULL;
17static TidyRealloc g_realloc = NULL;
18static TidyFree    g_free    = NULL;
19static TidyPanic   g_panic   = NULL;
20
21Bool TIDY_CALL tidySetMallocCall( TidyMalloc fmalloc )
22{
23  g_malloc  = fmalloc;
24  return yes;
25}
26Bool TIDY_CALL tidySetReallocCall( TidyRealloc frealloc )
27{
28  g_realloc = frealloc;
29  return yes;
30}
31Bool TIDY_CALL tidySetFreeCall( TidyFree ffree )
32{
33  g_free    = ffree;
34  return yes;
35}
36Bool TIDY_CALL tidySetPanicCall( TidyPanic fpanic )
37{
38  g_panic   = fpanic;
39  return yes;
40}
41
42void FatalError( ctmbstr msg )
43{
44  if ( g_panic )
45    g_panic( msg );
46  else
47  {
48    /* 2 signifies a serious error */
49    fprintf( stderr, "Fatal error: %s\n", msg );
50    exit(2);
51  }
52}
53
54void* MemAlloc( size_t size )
55{
56    void *p = ( g_malloc ? g_malloc(size) : malloc(size) );
57    if ( !p )
58        FatalError("Out of memory!");
59    return p;
60}
61
62void* MemRealloc( void* mem, size_t newsize )
63{
64    void *p;
65    if ( mem == NULL )
66        return MemAlloc( newsize );
67
68    p = ( g_realloc ? g_realloc(mem, newsize) : realloc(mem, newsize) );
69    if (!p)
70        FatalError("Out of memory!");
71    return p;
72}
73
74void MemFree( void* mem )
75{
76    if ( mem )
77    {
78        if ( g_free )
79            g_free( mem );
80        else
81            free( mem );
82    }
83}
84
85void ClearMemory( void *mem, size_t size )
86{
87    memset(mem, 0, size);
88}
89
90