Azinix

safe_mem.c

Go to the documentation of this file.
00001 
00002 #include "util.h"
00003 
00004 /**AutomaticStart*************************************************************/
00005 
00006 /*---------------------------------------------------------------------------*/
00007 /* Static function prototypes                                                */
00008 /*---------------------------------------------------------------------------*/
00009 
00010 
00011 /**AutomaticEnd***************************************************************/
00012 
00013 
00014 /** \file safe_mem.c
00015  *
00016  \brief These are interface routines to be placed between a program and the
00017  system memory allocator.  
00018 
00019  It forces well-defined semantics for several 'borderline' cases:
00020 
00021  <ul>
00022  <li>   <code>malloc()</code> of a 0 size object is guaranteed to return something
00023         which is not 0, and can safely be freed (but not dereferenced)
00024  <li>   <code>free()</code> accepts (silently) an 0 pointer
00025  <li>   realloc of a 0 pointer is allowed, and is equiv. to <code>malloc()</code>
00026  </ul>
00027 
00028 */
00029 
00030 
00031 /**
00032   * \brief Safe malloc
00033   */
00034 
00035 char *
00036 MMalloc (int size)
00037 {
00038   char *p;
00039 
00040   if (size <= 0)
00041     {
00042       size = sizeof (int);
00043     }
00044   if ((p = (char *) malloc ((unsigned) size)) == NIL (char))
00045     {
00046       (void) fflush (stdout);
00047       (void) fprintf (stderr, "\nout of memory allocating %ld bytes\n", size);
00048       exit (1);
00049     }
00050   return p;
00051 }
00052 
00053 
00054 /**
00055   * \brief Safe realloc
00056   */
00057 
00058 char *
00059 MMrealloc (char *obj, int size)
00060 {
00061   char *p;
00062 
00063   if (obj == NIL (char))
00064     {
00065       return MMalloc (size);
00066     }
00067   if (size <= 0)
00068     {
00069       size = sizeof (long);
00070     }
00071   if ((p = (char *) realloc (obj, (unsigned) size)) == NIL (char))
00072     {
00073       (void) fflush (stdout);
00074       (void) fprintf (stderr, "\nout of memory re-allocating %ld bytes\n",
00075               size);
00076       exit (1);
00077     }
00078   return p;
00079 }
00080 
00081 
00082 /**
00083   * \brief Safe free
00084   */
00085 
00086 void
00087 MMfree (char *obj)
00088 {
00089   if (obj != 0)
00090     {
00091       free (obj);
00092     }
00093 }