1 #ifndef IVL_ivl_alloc_H
2 #define IVL_ivl_alloc_H
3 /*
4  *  Copyright (C) 2010-2014  Cary R. (cygcary@yahoo.com)
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License along
17  *  with this program; if not, write to the Free Software Foundation, Inc.,
18  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20 
21 #ifdef __cplusplus
22 #  include <cstdlib>
23 #  include <cstdio>
24 #else
25 #  include <stdlib.h>
26 #  include <stdio.h>
27 #endif
28 
29 #if defined(__GNUC__)
30 /*
31  * Define a safer version of malloc().
32  */
33 
34 #define malloc(__ivl_size) \
35 ({ \
36 	/* To be safe we only evaluate the argument once. */ \
37       size_t __ivl_lsize = __ivl_size; \
38       void *__ivl_rtn = malloc(__ivl_lsize); \
39 	/* If we run out of memory then exit with a message. */ \
40       if ((__ivl_rtn == NULL) && (__ivl_lsize != 0)) { \
41 	    fprintf(stderr, "%s:%d: Error: malloc() ran out of memory.\n", \
42 	                    __FILE__, __LINE__); \
43 	    exit(1); \
44       } \
45       __ivl_rtn; \
46 })
47 
48 /*
49  * Define a safer version of realloc().
50  */
51 
52 #define realloc(__ivl_ptr, __ivl_size) \
53 ({ \
54 	/* To be safe we only evaluate the arguments once. */ \
55       void *__ivl_lptr = __ivl_ptr; \
56       size_t __ivl_lsize = __ivl_size; \
57       void *__ivl_rtn = realloc(__ivl_lptr, __ivl_lsize); \
58 	/* If we run out of memory then exit with a message. */ \
59       if ((__ivl_rtn == NULL) && (__ivl_lsize != 0)) { \
60 	    fprintf(stderr, "%s:%d: Error: realloc() ran out of memory.\n", \
61 	                    __FILE__, __LINE__); \
62 	    free(__ivl_lptr); \
63 	    exit(1); \
64       } \
65       __ivl_rtn; \
66 })
67 
68 /*
69  * Define a safer version of calloc().
70  */
71 
72 #define calloc(__ivl_count, __ivl_size) \
73 ({ \
74 	/* To be safe we only evaluate the arguments once. */ \
75       size_t __ivl_lcount = __ivl_count; \
76       size_t __ivl_lsize = __ivl_size; \
77       void *__ivl_rtn = calloc(__ivl_lcount, __ivl_lsize); \
78 	/* If we run out of memory then exit with a message. */ \
79       if ((__ivl_rtn == NULL) && (__ivl_lcount != 0) && (__ivl_lsize != 0)) { \
80 	    fprintf(stderr, "%s:%d: Error: calloc() ran out of memory.\n", \
81 	                    __FILE__, __LINE__); \
82 	    exit(1); \
83       } \
84       __ivl_rtn; \
85 })
86 #endif
87 
88 #endif /* IVL_ivl_alloc_H */
89