source: vis_dev/cusp-1.1/src/util/safe_mem.c @ 64

Last change on this file since 64 was 12, checked in by cecile, 13 years ago

cusp added

File size: 2.0 KB
Line 
1/*
2 * Revision Control Information
3 *
4 * $Id: safe_mem.c,v 1.1.1.1 2008-11-14 20:40:10 hhkim Exp $
5 *
6 */
7/* LINTLIBRARY */
8
9#include "util.h"
10
11/*
12 *  These are interface routines to be placed between a program and the
13 *  system memory allocator. 
14 *
15 *  It forces well-defined semantics for several 'borderline' cases:
16 *
17 *      malloc() of a 0 size object is guaranteed to return something
18 *          which is not 0, and can safely be freed (but not dereferenced)
19 *      free() accepts (silently) an 0 pointer
20 *      realloc of a 0 pointer is allowed, and is equiv. to malloc()
21 *      For the IBM/PC it forces no object > 64K; note that the size argument
22 *          to malloc/realloc is a 'long' to catch this condition
23 *
24 *  The function pointer MMoutOfMemory() contains a vector to handle a
25 *  'out-of-memory' error (which, by default, points at a simple wrap-up
26 *  and exit routine).
27 */
28
29void (*MMoutOfMemory)(unsigned long) = MMout_of_memory;
30
31
32/* MMout_of_memory -- out of memory for lazy people, flush and exit */
33void
34MMout_of_memory(unsigned long size)
35{
36  (void) fflush(stdout);
37  (void) fprintf(stderr, "\nout of memory allocating %lu bytes\n", size);
38  exit(1);
39}
40
41
42void *
43MMalloc(unsigned long size)
44{
45  void *p;
46
47#ifdef IBMPC
48  if (size > 65000L) {
49    if (MMoutOfMemory != (void (*)(unsigned long)) 0) (*MMoutOfMemory)(size);
50    return NIL(void);
51  }
52#endif
53  if (size == 0) size = sizeof(long);
54  if ((p = malloc(size)) == NIL(void)) {
55    if (MMoutOfMemory != (void (*)(unsigned long)) 0) (*MMoutOfMemory)(size);
56    return NIL(void);
57  }
58  return p;
59}
60
61
62void *
63MMrealloc(void *obj, unsigned long size)
64{
65  void *p;
66
67#ifdef IBMPC
68  if (size > 65000L) {
69    if (MMoutOfMemory != (void (*)(unsigned long)) 0) (*MMoutOfMemory)(size);
70    return NIL(void);
71  }
72#endif
73  if (obj == NIL(void)) return MMalloc(size);
74  if (size <= 0) size = sizeof(long);
75  if ((p = realloc(obj, size)) == NIL(void)) {
76    if (MMoutOfMemory != (void (*)(unsigned long)) 0) (*MMoutOfMemory)(size);
77    return NIL(void);
78  }
79  return p;
80}
81
82
83void
84MMfree(void *obj)
85{
86  if (obj != 0) {
87    free(obj);
88  }
89}
Note: See TracBrowser for help on using the repository browser.