[EMAIL PROTECTED] writes:
> [about alloca vs malloc]
>
> If you allocate with malloc and then accidentally overwrite it, you get a
> corrupted heap.
> If you allocate with alloca and then accidentally overwrite it, you get a
> corrupted stack.
>
> Guess which is easier to notice :-)
Seriously, which? Stack corruptions are notorious, but heap
corruption are no better in my book. (Not to mention that one sort of
corruption often *leads* to the other.)
> Besides, alloca is a GCC builtin (IIRC), so you you don't have to
> worry about its implementation (the GCC folks do :).
It's a Gcc builtin under Gcc. Most modern Unix compilers support it
too.
> As long as you have the stack to allocate from, it's as transparent
> as declaring automatic arrays with variable length. e.g.
>
> p = alloca( strlen(s) );
This hurts to see; you must have meant "strlen(s) + 1". :-)
> is almost the same as
>
> char a[ strlen(s) ], p=a;
> /* this is a legal GCC extension */
It's also legal C9X code.
But the significant difference between VLA's (Variable Length Arrays)
and alloca is that they differ in scope, hence it's dangerous to mix
them. For instance, these two things are very different:
while (CONDITION)
{
char *p = alloca (n);
...
}
and:
while (CONDITION)
{
char p[n];
...
}
The first one will keep allocating new memory which will get freed
only after the function exits. The latter will free memory after the
end of each block, hence allocating new memory every time.
However, here is the truly dangerous part:
char *p1;
if (CONDITION)
{
char p2[n];
...
p1 = alloca (m);
}
/* Is it now legal to access P1? */
This is undefined. If VLA's and alloca are based on a simple stack,
which they have to be, "freeing" P2 will also trash P1. (And in fact
the Gcc manual documents this.) Note that in the general case the
compiler cannot "smartly" rearrange the code to allocate P1 before P2
because N and M might not be known before their respective usage.
The "standard C" response to this is "don't use alloca" because alloca
has never been "standard" in the first place. But as long as there
are large bodies of code that use alloca and almost no compilers speak
C9X, I will continue to prefer alloca over VLA's.