1 /* this code is stolen from the links browser, it was written by Mikulas Patocka */
11 #define inline __inline
15 #define DUMMY ((void *)-1L)
17 void do_not_optimize_here(void *p
);
18 void check_memory_leaks(void);
20 void error(char *, ...);
22 #define error(...) while(0);
24 void debug_msg(char *, ...);
25 void int_error(char *, ...);
30 #define x_calloc(x) calloc((x), 1)
32 static inline void *x_calloc(size_t x
)
35 if ((p
= malloc(x
))) memset(p
, 0, x
);
40 #define internal errfile = __FILE__, errline = __LINE__, int_error
41 #define debug errfile = __FILE__, errline = __LINE__, debug_msg
46 extern void *debug_mem_alloc(char *, int, size_t);
47 extern void *debug_mem_calloc(char *, int, size_t);
48 extern void debug_mem_free(char *, int, void *);
49 extern void *debug_mem_realloc(char *, int, void *, size_t);
50 extern void set_mem_comment(void *, char *, int);
52 #define mem_alloc(x) debug_mem_alloc(__FILE__, __LINE__, x)
53 #define mem_calloc(x) debug_mem_calloc(__FILE__, __LINE__, x)
54 #define mem_free(x) debug_mem_free(__FILE__, __LINE__, x)
55 #define mem_realloc(x, y) debug_mem_realloc(__FILE__, __LINE__, x, y)
59 static inline void *mem_alloc(size_t size
)
62 if (!size
) return DUMMY
;
63 if (!(p
= malloc(size
))) {
64 error("ERROR: out of memory (malloc returned NULL)\n");
70 static inline void *mem_calloc(size_t size
)
73 if (!size
) return DUMMY
;
74 if (!(p
= x_calloc(size
))) {
75 error("ERROR: out of memory (calloc returned NULL)\n");
81 static inline void mem_free(void *p
)
83 if (p
== DUMMY
) return;
85 // internal("mem_free(NULL)");
91 static inline void *mem_realloc(void *p
, size_t size
)
93 if (p
== DUMMY
) return mem_alloc(size
);
95 // internal("mem_realloc(NULL, %d)", size);
102 if (!(p
= realloc(p
, size
))) {
103 error("ERROR: out of memory (realloc returned NULL)\n");
109 static inline void *debug_mem_alloc(char *f
, int l
, size_t s
) { f
=f
; l
=l
; return mem_alloc(s
); }
110 static inline void *debug_mem_calloc(char *f
, int l
, size_t s
) { f
=f
; l
=l
; return mem_calloc(s
); }
111 static inline void debug_mem_free(char *f
, int l
, void *p
) { f
=f
; l
=l
; mem_free(p
); }
112 static inline void *debug_mem_realloc(char *f
, int l
, void *p
, size_t s
) { f
=f
; l
=l
; return mem_realloc(p
, s
); }
113 static inline void set_mem_comment(void *p
, char *c
, int l
) {p
=p
; c
=c
; l
=l
;}
119 #endif /* __ERROR_H */