onstack.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright 1997, University Corporation for Atmospheric Research
  3. * See netcdf/COPYRIGHT file for copying and redistribution conditions.
  4. */
  5. /* $Id: onstack.h,v 2.7 2006/09/15 20:40:39 ed Exp $ */
  6. #ifndef _ONSTACK_H_
  7. #define _ONSTACK_H_
  8. /**
  9. * This file provides definitions which allow us to
  10. * "allocate" arrays on the stack where possible.
  11. * (Where not possible, malloc and free are used.)
  12. *
  13. * The macro ALLOC_ONSTACK(name, type, nelems) is used to declare
  14. * an array of 'type' named 'name' which is 'nelems' long.
  15. * FREE_ONSTACK(name) is placed at the end of the scope of 'name'
  16. * to call 'free' if necessary.
  17. *
  18. * The macro ALLOC_ONSTACK wraps a call to alloca() on most systems.
  19. */
  20. #if HAVE_ALLOCA
  21. /*
  22. * Implementation based on alloca()
  23. */
  24. #if defined(__GNUC__)
  25. # if !defined(alloca)
  26. # define alloca __builtin_alloca
  27. # endif
  28. #else
  29. # if HAVE_ALLOCA_H
  30. # include <alloca.h>
  31. # elif defined(_AIX)
  32. # pragma alloca
  33. # endif /* HAVE_ALLOCA_H */
  34. #endif /* __GNUC__ */
  35. # if !defined(ALLOCA_ARG_T)
  36. # define ALLOCA_ARG_T int /* the usual type of the alloca argument */
  37. # endif
  38. # define ALLOC_ONSTACK(name, type, nelems) \
  39. type *const name = (type *) alloca((ALLOCA_ARG_T)((nelems) * sizeof(type)))
  40. # define FREE_ONSTACK(name)
  41. #elif defined(_CRAYC) && !defined(__crayx1) && !__cplusplus && __STDC__ > 1
  42. /*
  43. * Cray C allows sizing of arrays with non-constant values.
  44. */
  45. # define ALLOC_ONSTACK(name, type, nelems) \
  46. type name[nelems]
  47. # define FREE_ONSTACK(name)
  48. #else
  49. /*
  50. * Default implementation. When all else fails, use malloc/free.
  51. */
  52. # define ALLOC_ONSTACK(name, type, nelems) \
  53. type *const name = (type *) malloc((nelems) * sizeof(type))
  54. # define FREE_ONSTACK(name) \
  55. free(name)
  56. #endif
  57. #endif /* _ONSTACK_H_ */