1 /* Jitter: safe malloc wrappers. 2 3 Copyright (C) 2017, 2020 Luca Saiu 4 Written by Luca Saiu 5 6 This file is part of Jitter. 7 8 Jitter is free software: you can redistribute it and/or modify 9 it under the terms of the GNU General Public License as published by 10 the Free Software Foundation, either version 3 of the License, or 11 (at your option) any later version. 12 13 Jitter is distributed in the hope that it will be useful, 14 but WITHOUT ANY WARRANTY; without even the implied warranty of 15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 GNU General Public License for more details. 17 18 You should have received a copy of the GNU General Public License 19 along with Jitter. If not, see <http://www.gnu.org/licenses/>. */ 20 21 22 #ifndef JITTER_MALLOC_H_ 23 #define JITTER_MALLOC_H_ 24 25 #include <stdlib.h> 26 27 28 /* Gnulib "malloc" attribute workaround: disabling. 29 * ************************************************************************** */ 30 31 /* When Gnulib is used it may redefine "malloc" as a macro, in order to use a 32 fixed version on some platforms. That is all good, except that having it 33 defined as a macro generates very distracting warnings when "malloc" is used 34 as a function attribute, and breaks the intended optimization. Let's avoid 35 that. */ 36 #ifdef malloc 37 # define JITTER_MALLOC_WAS_DEFINED_AS_A_MACRO 1 38 # define JITTER_MALLOC_PREVIOUS_DEFINITION malloc 39 # undef malloc 40 #endif // #ifdef malloc 41 42 43 44 45 /* Safe malloc wrappers, not using Gnulib for minimality. 46 * ************************************************************************** */ 47 48 /* Allocate char_no chars with malloc and return its result, as long as it is 49 non-NULL (or the requested size is zero); fail fatally if allocation 50 fails. 51 This is a trivial wrapper around malloc which fails fatally on error, instead 52 of returning a result to check. */ 53 void * 54 jitter_xmalloc (size_t char_no) 55 __attribute__ ((malloc)); 56 57 /* Allocate char_no chars with realloc in place of the pointed buffer and return 58 realloc's result, as long as it is non-NULL (or the new requested size is 59 zero); fail fatally on reallocation failure. 60 This is a trivial wrapper around realloc which fails fatally on error, 61 instead of returning a result to check. */ 62 void * 63 jitter_xrealloc (void *previous, size_t char_no) 64 __attribute__ ((warn_unused_result)); 65 66 67 68 69 /* Gnulib "malloc" attribute workaround: re-enabling. 70 * ************************************************************************** */ 71 72 /* Restore the previous malloc redefinition from Gnulib, if any. This assumes 73 that malloc was defined without arguments, which is currently the case. */ 74 #ifdef JITTER_MALLOC_WAS_DEFINED_AS_A_MACRO 75 # define malloc JITTER_MALLOC_PREVIOUS_DEFINITION 76 #endif 77 78 79 #endif // #ifndef JITTER_MALLOC_H_ 80