alloca()

alloca() is like malloc() except that it allocates memory on the stack of the current function. The memory does need to be freed - it will be automatically be freed once the function returns. This also limits the situations where alloca() can be used. However, where it can be used, alloca() generally results in better performance than malloc().

Unfortunately, alloca() is not part of ANSI C, and is not available on all systems. To write code that can work on all systems, we can do one of the following:

For the third approach, define the following:


	#if( SUPPORTS_ALLOCA )
	  #define xalloc_stack(_t)	((_t*)alloca(sizeof(_t)))
	  #define xnalloc_stack(_t,_n)	((_t*)alloca(sizeof(_t)*(_n)))

	  #define xfree_stack(_t,_p)	((void)0)
	  #define xnfree_stack(_t,_n,_p) ((void)0)
	#else
	  #define xalloc_stack(_t)	xalloc(_t)
	  #define xnalloc_stack(_t,_n)	xnalloc(_t,_n)

	  #define xfree_stack(_t,_p)	xfree(_t,_p)
	  #define xnfree_stack(_t,_n,_p) xnfree(_t,_n,_p)
	#endif

Whenever one allocates a memory block using xalloc_stack(), "free" it at the end of the function, or some point earlier in the function, using xfree_stack(). This allows the use of stack allocation, where available, but allows us to switch to heap allocation without leaking memory.

As an example:


	void
	example_func(
		int	N
		)
	{
	  int *	temp = xnalloc_stack(int, N);

	  /* ... other stuff */

	  xnfree_stack(int, N, temp);
	}


Next Prev Main Top Feedback