[comp.lang.c] Alloca: Its use is hazardous to the health of your program?

andychoi@ocf.berkeley.edu (Andrew Choi) (05/31/90)

Hi everyone.

From everyone I talked to, they seem to suggest that system call "alloca"
is bad and should not be used because it is both machine- and compiler-
dependent.  The man pages of "alloca" on several different machines seem
to confirm that.

However, is it really that machine-dependent that its use should be
absolutely forbidden?  Has anyone ever run into trouble because of the
use "alloca".  Further, how would you rewrite the following piece
of code without using alloca:

int foo(int n)
{
	char *a = (char *) alloca(n);

	fgets(a, n, stdin);
	return strlen(a);
}

I know you can easily rewrite the above program using "malloc", but that
will mean an extra variable "sl" to store the length of a, plus an extra 
"free" statement at the end.  However, the above seems to be so
concise ....

One last question:  Why is alloca so machine-dependent?  It seems that
		    it shouldn't be ...

Any help or suggestion is GREATLY appreciated.

Name:  Andrew Choi			Phone: (415) 848-5658
Internet Address:  andychoi@ocf.berkeley.edu
#include <std/disclaimer.h>

karl@haddock.ima.isc.com (Karl Heuer) (06/08/90)

In article <1990May31.004024.29385@agate.berkeley.edu> andychoi@ocf.berkeley.edu (Andrew Choi) writes:
>One last question:  Why is alloca so machine-dependent?  It seems that
>it shouldn't be ...

If it's implemented as a front-end to malloc(), then it's hard to make sure
the free() gets done when the function ends.

If it's implemented by expanding the stack frame, then on machines that have
no frame pointer it can't be done without assistance from a compiler builtin.

Karl W. Z. Heuer (karl@ima.ima.isc.com or harvard!ima!karl), The Walking Lint