chiark / gitweb /
Import upstream sources.
[cparse] / mem.c
1 /*
2  * This file is part of Cmarsh
3  * Copyright (C) 2004 Richard Kettlewell
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA
19  */
20
21 #include "cparse.h"
22
23 #if USE_GC
24 # include <gc.h>
25 #else
26 static void *GC_malloc(size_t n) {
27   void *ptr;
28
29   if((ptr = malloc(n)))
30     memset(ptr, 0, n);
31   return ptr;
32 }
33
34 static void *GC_realloc(void *ptr, size_t n) {
35   return realloc(ptr, n);
36 }
37
38 static void *GC_malloc_atomic(size_t n) {
39   return malloc(n);
40 }
41 #endif
42
43 void *xmalloc(size_t n) {
44   void *ptr;
45
46   if(!(ptr = GC_malloc(n)) && n)
47     fatal(errno, "error allocating memory");
48   return ptr;
49 }
50
51 void *xrealloc(void *ptr, size_t n) {
52   if(!(ptr = GC_realloc(ptr, n)) && n)
53     fatal(errno, "error allocating memory");
54   return ptr;
55 }
56
57 void *xmalloc_noptr(size_t n) {
58   void *ptr;
59
60   if(!(ptr = GC_malloc_atomic(n)) && n)
61     fatal(errno, "error allocating memory");
62   return ptr;
63 }
64
65 void *xrealloc_noptr(void *ptr, size_t n) {
66   if(ptr == 0)
67     return xmalloc_noptr(n);
68   if(!(ptr = GC_realloc(ptr, n)) && n)
69     fatal(errno, "error allocating memory");
70   return ptr;
71 }
72
73 char *xstrdup(const char *s) {
74   char *t;
75
76   if(!(t = GC_malloc_atomic(strlen(s) + 1)))
77     fatal(errno, "error allocating memory");
78   return strcpy(t, s);
79 }
80
81 char *xstrndup(const char *s, size_t n) {
82   char *t;
83
84   if(!(t = GC_malloc_atomic(n + 1)))
85     fatal(errno, "error allocating memory");
86   memcpy(t, s, n);
87   t[n] = 0;
88   return t;
89 }
90
91 /*
92 Local Variables:
93 c-basic-offset:2
94 comment-column:40
95 End:
96 */