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 | |
---|
7 | #ifndef _ONSTACK_H_ |
---|
8 | #define _ONSTACK_H_ |
---|
9 | /** |
---|
10 | * This file provides definitions which allow us to |
---|
11 | * "allocate" arrays on the stack where possible. |
---|
12 | * (Where not possible, malloc and free are used.) |
---|
13 | * |
---|
14 | * The macro ALLOC_ONSTACK(name, type, nelems) is used to declare |
---|
15 | * an array of 'type' named 'name' which is 'nelems' long. |
---|
16 | * FREE_ONSTACK(name) is placed at the end of the scope of 'name' |
---|
17 | * to call 'free' if necessary. |
---|
18 | * |
---|
19 | * The macro ALLOC_ONSTACK wraps a call to alloca() on most systems. |
---|
20 | */ |
---|
21 | |
---|
22 | #if HAVE_ALLOCA |
---|
23 | /* |
---|
24 | * Implementation based on alloca() |
---|
25 | */ |
---|
26 | |
---|
27 | #if defined(__GNUC__) |
---|
28 | # if !defined(alloca) |
---|
29 | # define alloca __builtin_alloca |
---|
30 | # endif |
---|
31 | #else |
---|
32 | # if HAVE_ALLOCA_H |
---|
33 | # include <alloca.h> |
---|
34 | # elif defined(_AIX) |
---|
35 | # pragma alloca |
---|
36 | # endif /* HAVE_ALLOCA_H */ |
---|
37 | #endif /* __GNUC__ */ |
---|
38 | |
---|
39 | # if !defined(ALLOCA_ARG_T) |
---|
40 | # define ALLOCA_ARG_T int /* the usual type of the alloca argument */ |
---|
41 | # endif |
---|
42 | |
---|
43 | # define ALLOC_ONSTACK(name, type, nelems) \ |
---|
44 | type *const name = (type *) alloca((ALLOCA_ARG_T)((nelems) * sizeof(type))) |
---|
45 | |
---|
46 | # define FREE_ONSTACK(name) |
---|
47 | |
---|
48 | #elif defined(_CRAYC) && !defined(__crayx1) && !__cplusplus && __STDC__ > 1 |
---|
49 | /* |
---|
50 | * Cray C allows sizing of arrays with non-constant values. |
---|
51 | */ |
---|
52 | |
---|
53 | # define ALLOC_ONSTACK(name, type, nelems) \ |
---|
54 | type name[nelems] |
---|
55 | |
---|
56 | # define FREE_ONSTACK(name) |
---|
57 | |
---|
58 | #else |
---|
59 | /* |
---|
60 | * Default implementation. When all else fails, use malloc/free. |
---|
61 | */ |
---|
62 | |
---|
63 | # define ALLOC_ONSTACK(name, type, nelems) \ |
---|
64 | type *const name = (type *) malloc((nelems) * sizeof(type)) |
---|
65 | |
---|
66 | # define FREE_ONSTACK(name) \ |
---|
67 | free(name) |
---|
68 | |
---|
69 | #endif |
---|
70 | |
---|
71 | #endif /* _ONSTACK_H_ */ |
---|