The C Standard has nothing to say about the behavior of alloca()
. Some compilers use the stack in a very predictable fashion, and access automatic variables using a largely-redundant frame pointer. On such compilers, it's possible to reserve space on the stack by simply subtracting a value from the stack pointer, without the compiler having to know or care about the reservation in question. Such code will break badly, however, if the compiler uses the stack in ways that the application wasn't expecting.
I don't think that something like:
int *p = 0;
if (!foo(1,2,3))
goto skip_alloca;
p=alloca(46);
skip_alloca:
bar(4,5,6);
...
is apt to be any more dangerous than:
int *p = 0;
if (foo(1,2,3))
p=alloca(46);
bar(4,5,6);
...
If there is no residue on the stack from the function call at the time the alloca()
is performed, either operation would likely be safe. If there is residue on the stack at the time of the alloca (e.g. because the compiler opts to defer cleanup of foo
's arguments until after the call to bar
) that would make alloca()
misbehave badly. Using the goto
version of the code might actually be safer than the version with if
, because it would be harder for a compiler to identify that deferring the cleanup from foo
might be advantageous.