1 /* grecs - Gray's Extensible Configuration System
2 Copyright (C) 2007-2016 Sergey Poznyakoff
3
4 Grecs is free software; you can redistribute it and/or modify it
5 under the terms of the GNU General Public License as published by the
6 Free Software Foundation; either version 3 of the License, or (at your
7 option) any later version.
8
9 Grecs is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License along
15 with Grecs. If not, see <http://www.gnu.org/licenses/>. */
16
17 #ifdef HAVE_CONFIG_H
18 # include <config.h>
19 #endif
20 #include <grecs.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <errno.h>
24
25 static void *
def_malloc_fun(size_t size)26 def_malloc_fun(size_t size)
27 {
28 return malloc(size);
29 }
30
31 static void *
def_realloc_fun(void * ptr,size_t size)32 def_realloc_fun(void *ptr, size_t size)
33 {
34 return realloc(ptr, size);
35 }
36
37 static void
def_free_fun(void * ptr)38 def_free_fun(void *ptr)
39 {
40 free(ptr);
41 }
42
43 void *(*grecs_malloc_fun)(size_t size) = def_malloc_fun;
44 void *(*grecs_realloc_fun)(void *ptr, size_t size) = def_realloc_fun;
45 void (*grecs_alloc_die_fun)(void);
46 void (*grecs_free_fun)(void *) = def_free_fun;
47
48 void
grecs_free(void * ptr)49 grecs_free(void *ptr)
50 {
51 grecs_free_fun(ptr);
52 }
53
54 void *
grecs_malloc(size_t size)55 grecs_malloc(size_t size)
56 {
57 void *ptr = grecs_malloc_fun(size);
58 if (!ptr)
59 grecs_alloc_die();
60 return ptr;
61 }
62
63 void *
grecs_zalloc(size_t size)64 grecs_zalloc(size_t size)
65 {
66 void *ptr = grecs_malloc(size);
67 memset(ptr, 0, size);
68 return ptr;
69 }
70
71 void *
grecs_calloc(size_t nmemb,size_t size)72 grecs_calloc(size_t nmemb, size_t size)
73 {
74 return grecs_zalloc(nmemb * size);
75 }
76
77 void *
grecs_realloc(void * ptr,size_t size)78 grecs_realloc(void *ptr, size_t size)
79 {
80 void *newptr = grecs_realloc_fun(ptr, size);
81 if (!newptr)
82 grecs_alloc_die();
83 return newptr;
84 }
85
86 char *
grecs_strdup(const char * str)87 grecs_strdup(const char *str)
88 {
89 char *newstr = grecs_malloc(strlen(str) + 1);
90 return strcpy(newstr, str);
91 }
92
93 void
grecs_alloc_die(void)94 grecs_alloc_die(void)
95 {
96 if (grecs_alloc_die_fun)
97 grecs_alloc_die_fun();
98 grecs_error(NULL, ENOMEM, "fatal error");
99 exit(70); /* EX_SOFTWARE */
100 }
101