1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 #ifndef GMEM_WRAPPER_H
6 #define GMEM_WRAPPER_H
7
8 #define g_malloc_n g_malloc_n_
9 #define g_malloc0_n g_malloc0_n_
10 #define g_realloc_n g_realloc_n_
11 #include_next <glib/gmem.h>
12 #undef g_malloc_n
13 #undef g_malloc0_n
14 #undef g_realloc_n
15
16 #include <glib/gmessages.h>
17
18 #undef g_new
19 #define g_new(type, num) ((type*)g_malloc_n((num), sizeof(type)))
20
21 #undef g_new0
22 #define g_new0(type, num) ((type*)g_malloc0_n((num), sizeof(type)))
23
24 #undef g_renew
25 #define g_renew(type, ptr, num) ((type*)g_realloc_n(ptr, (num), sizeof(type)))
26
27 #define _CHECK_OVERFLOW(num, type_size) \
28 if (G_UNLIKELY(type_size > 0 && num > G_MAXSIZE / type_size)) { \
29 g_error("%s: overflow allocating %" G_GSIZE_FORMAT "*%" G_GSIZE_FORMAT \
30 " bytes", \
31 G_STRLOC, num, type_size); \
32 }
33
g_malloc_n(gsize num,gsize type_size)34 static inline gpointer g_malloc_n(gsize num, gsize type_size) {
35 _CHECK_OVERFLOW(num, type_size)
36 return g_malloc(num * type_size);
37 }
38
g_malloc0_n(gsize num,gsize type_size)39 static inline gpointer g_malloc0_n(gsize num, gsize type_size) {
40 _CHECK_OVERFLOW(num, type_size)
41 return g_malloc0(num * type_size);
42 }
43
g_realloc_n(gpointer ptr,gsize num,gsize type_size)44 static inline gpointer g_realloc_n(gpointer ptr, gsize num, gsize type_size) {
45 _CHECK_OVERFLOW(num, type_size)
46 return g_realloc(ptr, num * type_size);
47 }
48 #endif /* GMEM_WRAPPER_H */
49