Debian Codegraph @

xpa/xalloc.c

raw symbols SCIP
1 /*
2 * Copyright (c) 2004-2009 Smithsonian Astrophysical Observatory
3 */
4
5 /*
6 *
7 * xalloc -- safe memory allocation with error checking
8 *
9 */
10
11 /* this module is compiled within a funtools filter and must not require
12 the header files */
13 #ifdef FILTER_PTYPE
14 #define ANSI_FUNC 1
15 #else
16 #include <xalloc.h>
17 #endif
18
19 #define XALLOC_ERROR "ERROR: can't allocate memory (xalloc)\n"
20
21 #if XALLOC_SETJMP
22
23 static jmp_buf *xalloc_envptr=NULL;
24
25 #ifdef ANSI_FUNC
26 void xalloc_savejmp(jmp_buf *env)
27 #else
28 void xalloc_savejmp(env)
29 jmp_buf *env;
30 #endif
31 {
32 xalloc_envptr = env;
33 }
34 #endif
35
36
37 #ifdef ANSI_FUNC
38 static void _xalloc_error(void)
39 #else
40 static void _xalloc_error()
41 #endif
42 {
43 write(1, XALLOC_ERROR, strlen(XALLOC_ERROR));
44 #if XALLOC_SETJMP
45 if( xalloc_envptr )
46 longjmp(*xalloc_envptr, XALLOC_SETJMP);
47 else
48 #endif
49 exit(1);
50 }
51
52 #ifdef ANSI_FUNC
53 void *xmalloc(size_t n)
54 #else
55 void *xmalloc(n)
56 size_t n;
57 #endif
58 {
59 void *p;
60
61 if( !(p = (void *)malloc(n)) )
62 _xalloc_error();
63 return p;
64 }
65
66 #ifdef ANSI_FUNC
67 void *xcalloc (size_t n, size_t s)
68 #else
69 void *xcalloc (n, s)
70 size_t n, s;
71 #endif
72 {
73 void *p;
74
75 if( !(p = (void *)calloc(n, s)) )
76 _xalloc_error();
77 return p;
78 }
79
80 #ifdef ANSI_FUNC
81 void *xrealloc (void *p, size_t n)
82 #else
83 void *xrealloc (p, n)
84 void *p;
85 size_t n;
86 #endif
87 {
88 if( !p )
89 return xmalloc(n);
90 if( !(p = (void *)realloc(p, n)) )
91 _xalloc_error();
92 return p;
93 }
94
95 #ifdef ANSI_FUNC
96 void xfree (void *p)
97 #else
98 void xfree (p)
99 void *p;
100 #endif
101 {
102 if( p )
103 free(p);
104 }
105
106 #ifdef ANSI_FUNC
107 char *xstrdup (char *s)
108 #else
109 char *xstrdup (s)
110 char *s;
111 #endif
112 {
113 if( s )
114 return((char *)strcpy((char *)xmalloc((size_t)strlen(s)+1), s));
115 else
116 return NULL;
117 }