On Mon, 18 Jun 2001, Hrvoje Niksic wrote:
>
> * Reduced memory fragmentation -- you don't need to worry about
> thousands of small mallocs fragmenting your heap, alloca always
> allocates and flawlessly frees stuff off the stack.
This is why many people allocate all the memory they will need at the
beginning, and either never allocate memory again, or reallocate it (sensibly)
as needed.
> * Faster resulting code -- alloca generates the code that simply moves
> the stack pointer. malloc on the other hand is a genuine function
> call which needs to search the heap for a "good match", resize the
> heap if necessary, handle freeing, and be all around as fast as a
> rabbit and as memory-efficient as the proverbial Scott with his
> money, all at the same time. Obviously, one of these has to suffer.
alloca is faster, but the difference is measured in microseconds.
Considering that a single ping may be hundreds of milliseconds, this is
trivial. Also malloc is guaranteed to return NULL if the memory isn't
available, and can be recovered from that way... alloca is just as safe as
declaring a fixed-size array larger than the stack size; it's *not* guaranteed
to return at all, unless you know the amount allocated is less than your stack
size. And if you know in advance how much space the array will need, you could
have declared it statically anyway.
> So far, the amount of headache has been 0, whereas the benefits have
> been significant.
Until now, perhaps :)
--
/* Eric */main(s,i,j,k,c){char*p=malloc(s=1),*a=p+(*p=i=j=k=0)/* Bock */
;while(~(*a=getchar())&&(++a-p<s||(a=(p=realloc(p,s+s))+s)&&(s+=s))||(*a
=0));for(a=malloc(s=1),*a=0;(c=p[i])&&(c=='+'&&++a[j]||c=='-'&&--a[j]||c
=='>'&&(++j<s||(a=realloc(a,s+s))&&memset(a+s,0,s)&&(s+=s))||c=='<'&&j--
||c=='.'&&~putchar(a[j])||c==','&&~(a[j]=getchar()))|!strchr("><.,",c);i
++)while((c=='['&&!a[j]||c==']'&&a[j])&&(k+=(p[i]=='[')-(p[i]==']'))&&p[
i+=c/* Brainf*** */=='[']&&(/* worse than */i-=c==']'/* this sig! */));}