xmalloca.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Safe automatic memory allocation with out of memory checking.
  2. Copyright (C) 2003, 2005, 2007, 2009-2013 Free Software Foundation, Inc.
  3. Written by Bruno Haible <bruno@clisp.org>, 2003.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #ifndef _XMALLOCA_H
  15. #define _XMALLOCA_H
  16. #include "malloca.h"
  17. #include "xalloc.h"
  18. #ifdef __cplusplus
  19. extern "C" {
  20. #endif
  21. /* xmalloca(N) is a checking safe variant of alloca(N). It allocates N bytes
  22. of memory allocated on the stack, that must be freed using freea() before
  23. the function returns. Upon failure, it exits with an error message. */
  24. #if HAVE_ALLOCA
  25. # define xmalloca(N) \
  26. ((N) < 4032 - sa_increment \
  27. ? (void *) ((char *) alloca ((N) + sa_increment) + sa_increment) \
  28. : xmmalloca (N))
  29. extern void * xmmalloca (size_t n);
  30. #else
  31. # define xmalloca(N) \
  32. xmalloc (N)
  33. #endif
  34. /* xnmalloca(N,S) is an overflow-safe variant of xmalloca (N * S).
  35. It allocates an array of N objects, each with S bytes of memory,
  36. on the stack. S must be positive and N must be nonnegative.
  37. The array must be freed using freea() before the function returns.
  38. Upon failure, it exits with an error message. */
  39. #if HAVE_ALLOCA
  40. /* Rely on xmalloca (SIZE_MAX) calling xalloc_die (). */
  41. # define xnmalloca(n, s) \
  42. xmalloca (xalloc_oversized ((n), (s)) ? (size_t) (-1) : (n) * (s))
  43. #else
  44. # define xnmalloca(n, s) \
  45. xnmalloc ((n), (s))
  46. #endif
  47. #ifdef __cplusplus
  48. }
  49. #endif
  50. #endif /* _XMALLOCA_H */