[comp.sys.mac.programmer] use of alloca

janin@tybalt.caltech.edu (Adam L. Janin) (10/10/88)

Thanks to everyone who sent replies about Bison!

There is a much easier way to allocate stuff on the stack in C than using
alloca.  Variable declarations can be put after ANY open brace.  The scope of
the variable is local to the set of braces.  For example:
for (a = 0; a < 10; a++) {
	int x;
	...
	printf("%d", x);	/*  Works correctly	*/
	...
}
printf("%d", x);	/*  Does not work.  Variable not defined here.  */

etc.

Although this works, it is sometimes difficult to read code that contains
statements like this, since it can be hard to find the variable declarations.

	Adam Janin
	janin@tybalt.caltech.edu  or  janin@csvax.caltech.edu

earleh@eleazar.dartmouth.edu (Earle R. Horton) (10/10/88)

In article <8264@cit-vax.Caltech.Edu> janin@tybalt.caltech.edu (Adam L. Janin) writes:
>Thanks to everyone who sent replies about Bison!
>
>There is a much easier way to allocate stuff on the stack in C than using
>alloca.  Variable declarations can be put after ANY open brace.  The scope of
>the variable is local to the set of braces.  For example:
...

This technique does not work when the local variable is an array, the size of
which is not known until run time.  On systems where alloca() works, it is by
far the easiest way to obtain storage which is local to a procedure, and which
vanishes when the procedure exits.  This is most useful in a procedure which is
set up to abort via a long jump, or which has several return statements in it,
and one would like to be able to exit the routine without having to explicitly
free up several arrays at each return point.  (Or at a signal handler.)

The places in Bison where alloca() is used could easily be converted to malloc(),
since the flow of control in these routines is relatively straightforward, and
it would be simple to free up storage on procedure exit.  I think the reason
alloca() is used there is "historical," i.e. GNU code is full of alloca().

The main objections to the use of alloca() seem to be that it is not portable,
i.e. it is not easy to implement in some architectures.  It's a good thing for
me I don't have to work with those architectures!  (For now, anyway.)

Earle R. Horton. 23 Fletcher Circle, Hanover, NH 03755
(603) 643-4109
Sorry, no fancy stuff, since this program limits my .signature to three