Path: utzoo!attcan!uunet!van-bc!jtc From: jtc@van-bc.wimsey.bc.ca (J.T. Conklin) Newsgroups: comp.lang.c Subject: Re: alloca() portability Keywords: portability, alloca Message-ID: <135@van-bc.wimsey.bc.ca> Date: 8 Nov 90 16:39:53 GMT References: <9032@ncar.ucar.edu> <499@taumet.com> <14377@smoke.brl.mil> Organization: UniFax Communications Inc., Vancouver, B.C., Canada Lines: 37 In article <14377@smoke.brl.mil> gwyn@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@wimsey.bc.ca