alloca() portability
J.T. Conklin
jtc at van-bc.wimsey.bc.ca
Fri Nov 9 03:39:53 AEST 1990
In article <14377 at smoke.brl.mil> gwyn at smoke.brl.mil (Doug Gwyn) writes:
>It is worth repeating over and over: DON'T WRITE CODE THAT USES alloca()!
>I provided my alloca() implementation solely in support of existing code
>that needs to be ported and for which fixing its use of alloca() would be
>too painful.
I agree that alloca() should not be used, but sometimes the low
overhead of alloca(), especially when implemented as a compiler
builtin, is just too good to pass up. In the cases were you feel you
can't live without alloca(), I suggest something like this:
#ifdef HAVE_WORKING_ALLOCA
#define ALLOCATE_LOCAL(n) alloca(n)
#define DEALLOCATE_LOCAL(m)
#else
#define ALLOCATE_LOCAL(n) malloc(n)
#define DEALLOCATE_LOCAL(m) free(m)
void foo(int bar)
{
char *s = ALLOCATE_LOCAL(bar);
...
DEALLOCATE_LOCAL(s);
return;
}
Make sure there is a DEALLOCATE_LOCAL() call before every point of
exit from your function, and you won't have any memory leaks.
I think this technique is used in the X Window sample servers.
--jtc
--
J.T. Conklin UniFax Communications Inc.
...!{uunet,ubc-cs}!van-bc!jtc, jtc at wimsey.bc.ca
More information about the Comp.lang.c
mailing list