1 /*
2 * Some memory allocation routines, they call abort() in case of failure
3 *
4 * Part of HTML-XML-utils, see:
5 * http://www.w3.org/Tools/HTML-XML-utils/
6 *
7 * Copyright © 1994-2003 World Wide Web Consortium
8 * See http://www.w3.org/Consortium/Legal/copyright-software
9 *
10 * Author: Bert Bos <bert@w3.org>
11 * Created: before 1995
12 **/
13 #include "config.h"
14 #include <stdlib.h>
15 #include <stdio.h>
16 #if STDC_HEADERS
17 # include <string.h>
18 #else
19 # ifndef HAVE_STRCHR
20 # define strchr index
21 # define strrchr rindex
22 # endif
23 #endif
24 #include "export.h"
25
26 #ifdef __export
27 #undef __FILE__ /* Don't expand while making the .e file */
28 #undef __LINE__ /* Don't expand while making the .e file */
29 #endif
30
31 #define fatal(msg) fatal3(msg, __FILE__, __LINE__)
32 #define new(p) if (((p)=malloc(sizeof(*(p))))); else fatal("out of memory")
33 #define dispose(p) if (!(p)) ; else (free((void*)p), (p) = (void*)0)
34 #define heapmax(p) 9999999 /* ? */
35 #define newstring(s) heap_newstring(s, __FILE__, __LINE__)
36 #define newnstring(s,n) heap_newnstring(s, n, __FILE__, __LINE__)
37 #define newarray(p,n) \
38 if (((p)=malloc((n)*sizeof(*(p))))); else fatal("out of memory")
39 #define renewarray(p,n) \
40 if (((p)=realloc(p,(n)*sizeof(*(p))))); else fatal("out of memory")
41
42 EXPORTDEF(fatal(msg))
EXPORTDEF(new (p))43 EXPORTDEF(new(p))
44 EXPORTDEF(dispose(p))
45 EXPORTDEF(heapmax(p))
46 EXPORTDEF(newstring(s))
47 EXPORTDEF(newnstring(s,n))
48 EXPORTDEF(newarray(p,n))
49 EXPORTDEF(renewarray(p,n))
50
51
52 EXPORT void fatal3(const char *s, const char *file, const unsigned int line)
53 {
54 fprintf(stderr, "%s (file %s, line %d)\n", s, file, line);
55 abort();
56 }
57
58
heap_newstring(const char * s,const char * file,const int line)59 EXPORT char * heap_newstring(const char *s, const char *file, const int line)
60 {
61 char *t;
62
63 if (!s) return NULL;
64 t = malloc((strlen(s) + 1) * sizeof(*t));
65 if (!t) fatal3("out of memory", file, line);
66 strcpy(t, s);
67 return t;
68 }
69
heap_newnstring(const char * s,const size_t n,const char * file,const int line)70 EXPORT char * heap_newnstring(const char *s, const size_t n,
71 const char *file, const int line)
72 {
73 char *t;
74
75 if (!s) return NULL;
76 t = malloc((n + 1) * sizeof(*t));
77 if (!t) fatal3("out of memory", file, line);
78 strncpy(t, s, n);
79 t[n] = '\0';
80 return t;
81 }
82