This function is not mentioned very often in this newsgroup but it
is a VERY useful function, implemented in most compilers.
And, unfortunately, *MIS*-implemented in many.
I think it is useful to point to it since many people that read this
newsgroup are newcomers, and they could benefit by using it.
This function is an allocation function, i.e. it is similar in
functionality to the malloc() function, but it has the advantage of
allocating from the stack instead of allocating from the heap.
Disadvantages:
- In all the implementations I have seen, it does NOT make any attempt
to detect stack overflow and return NULL on error. This is a
serious problem, the gets() of memory allocation.
- There is no way to free memory except by exiting the function, which
means that alloca() called within a loop can accumulate a lot of
no-longer-used storage. Well, that's just a situation where malloc()
should be used rather than alloca().
- It is not a standard C function.
- alloca(), when implemented not as a wrapper for malloc() but actually
allocating storage on the stack, cannot work reliably if the compiler
does not know that alloca() is being called, otherwise, there is a
tendancy for it to allocate blocks of memory in the middle of function
parameter lists, causing garbage to be passed to functions.
This means that if you take the address of alloca(), put it in a function
pointer, and then call it indirectly, unless the compiler can figure
out that it might be a call to alloca(), it is likely to malfunction.
(gcc on FreeBSD makes taking the address of alloca() fail, probably
the best way to avoid this.)
Test your version of alloca():
- Put the program below into a file.
- Add whatever header is needed to declare alloca().
- Compile it and run it.
- Verify that the first line of output contains "1 = 1" and the
third line contains "2 = 2". If not, something failed.
- When reporting results, include your processor, OS, version, compiler,
and it's version, and what compiler flags you used.
- Try and see if there are any differences with different optimization flags.
Incidentally, on i386, FreeBSD 6.2 with gcc 3.4.6, it seems to use
32 bytes each for alloca(3). No optimization, -O, -O2, and -O3 all
produce correct results.
It's intended that in this test program, the number of alloca()
calls exceeds the number of registers the compiler can use to pass
function parameters. If that's not the case for your platform,
edit accordingly.
#include <stdlib.h>
int main(int argc, char **argv)
{
printf("1 = %d\n%p %p %p %p %p %p %p %p %p %p %p\n2 = %d\n",
1,
alloca(3),
alloca(3),
alloca(3),
alloca(3),
alloca(3),
alloca(3),
alloca(3),
alloca(3),
alloca(3),
alloca(3),
alloca(3),
2);
exit(EXIT_SUCCESS);
}