exp2l: Work around a NetBSD 10.0/i386 bug.
[gnulib.git] / lib / xmalloca.h
bloba096511b1793539efed510b4acd27291d7e93130
1 /* Safe automatic memory allocation with out of memory checking.
2 Copyright (C) 2003, 2005, 2007, 2009-2024 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2003.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 #ifndef _XMALLOCA_H
19 #define _XMALLOCA_H
21 /* This file uses _GL_ATTRIBUTE_ALLOC_SIZE, _GL_ATTRIBUTE_DEALLOC,
22 _GL_ATTRIBUTE_MALLOC, _GL_ATTRIBUTE_RETURNS_NONNULL, HAVE_ALLOCA. */
23 #if !_GL_CONFIG_H_INCLUDED
24 #error "Please include config.h first."
25 #endif
27 #include "malloca.h"
28 #include "xalloc.h"
29 #include "xalloc-oversized.h"
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
37 /* xmalloca(N) is a checking safe variant of alloca(N). It allocates N bytes
38 of memory allocated on the stack, that must be freed using freea() before
39 the function returns. N should not have side effects.
40 Upon failure, it exits with an error message. */
41 #if HAVE_ALLOCA
42 # define xmalloca(N) \
43 ((N) < 4032 - (2 * sa_alignment_max - 1) \
44 ? (void *) (((uintptr_t) (char *) alloca ((N) + 2 * sa_alignment_max - 1) \
45 + (2 * sa_alignment_max - 1)) \
46 & ~(uintptr_t)(2 * sa_alignment_max - 1)) \
47 : xmmalloca (N))
48 extern void * xmmalloca (size_t n)
49 _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_DEALLOC (freea, 1)
50 _GL_ATTRIBUTE_ALLOC_SIZE ((1)) _GL_ATTRIBUTE_RETURNS_NONNULL;
51 #else
52 # define xmalloca(N) \
53 xmalloc (N)
54 #endif
56 /* xnmalloca(N,S) is an overflow-safe variant of xmalloca (N * S).
57 It allocates an array of N objects, each with S bytes of memory,
58 on the stack. S must be positive and N must be nonnegative,
59 and S and N should not have side effects.
60 The array must be freed using freea() before the function returns.
61 Upon failure, it exits with an error message. */
62 #if HAVE_ALLOCA
63 /* Rely on xmalloca (SIZE_MAX) calling xalloc_die (). */
64 # define xnmalloca(n, s) \
65 xmalloca (xalloc_oversized (n, s) ? (size_t) (-1) : (n) * (size_t) (s))
66 #else
67 # define xnmalloca(n, s) \
68 xnmalloc (n, s)
69 #endif
72 #ifdef __cplusplus
74 #endif
77 #endif /* _XMALLOCA_H */