home *** CD-ROM | disk | FTP | other *** search
/ Dr. CD ROM (Annual Premium Edition) / premium.zip / premium / IBMOS2_1 / SC621.ZIP / sc621 / xmalloc.c < prev    next >
C/C++ Source or Header  |  1992-06-01  |  1KB  |  84 lines

  1. /*
  2.  * A safer saner malloc, for careless programmers
  3.  * $Revision: 6.21 $
  4.  */
  5.  
  6. #include <stdio.h>
  7. #include <curses.h>
  8. #include "sc.h"
  9.  
  10. extern    char *malloc();
  11. extern    char *realloc();
  12. extern    void free();
  13. void    fatal();
  14.  
  15. #ifdef SYSV3
  16. extern void free();
  17. extern void exit();
  18. #endif
  19.  
  20. #define    MAGIC    (double)1234567890.12344
  21.  
  22. char *
  23. scxmalloc(n)
  24. unsigned n;
  25. {
  26.     register char *ptr;
  27.  
  28.     if ((ptr = malloc(n + sizeof(double))) == NULL)
  29.         fatal("scxmalloc: no memory");
  30.     *((double *) ptr) = MAGIC;        /* magic number */
  31.     return(ptr + sizeof(double));
  32. }
  33.  
  34. /* we make sure realloc will do a malloc if needed */
  35. char *
  36. scxrealloc(ptr, n)
  37. char    *ptr;
  38. unsigned n;
  39. {
  40.     if (ptr == NULL)
  41.         return(scxmalloc(n));
  42.  
  43.     ptr -= sizeof(double);
  44.     if (*((double *) ptr) != MAGIC)
  45.         fatal("scxrealloc: storage not scxmalloc'ed");
  46.  
  47.     if ((ptr = realloc(ptr, n + sizeof(double))) == NULL)
  48.         fatal("scxmalloc: no memory");
  49.     *((double *) ptr) = MAGIC;        /* magic number */
  50.     return(ptr + sizeof(double));
  51. }
  52.  
  53. void
  54. scxfree(p)
  55. char *p;
  56. {
  57.     if (p == NULL)
  58.         fatal("scxfree: NULL");
  59.     p -= sizeof(double);
  60.     if (*((double *) p) != MAGIC)
  61.         fatal("scxfree: storage not malloc'ed");
  62.     free(p);
  63. }
  64.  
  65. #ifdef PSC
  66. void
  67. fatal(str)
  68. char *str;
  69. {
  70.     (void) fprintf(stderr,"%s\n", str);
  71.     exit(1);
  72. }
  73. #else
  74. void
  75. fatal(str)
  76. char *str;
  77. {
  78.     deraw();
  79.     (void) fprintf(stderr,"%s\n", str);
  80.     diesave();
  81.     exit(1);
  82. }
  83. #endif /* PSC */
  84.