[vox-tech] dyanamic memory panacea

Micah Cowan vox-tech@lists.lugod.org
Tue, 16 Jul 2002 21:45:31 -0700


Peter Jay Salzman writes:
 > ok, not a panacea, but pretty cool nevertheless...
 > 
 > i was doing some reading and found a function alloca() which allocates
 > dynamic memory like malloc() and friends, but it gets memory from the
 > current stack frame instead of the heap.
 > 
 > the obvious advantage is that the memory is deallocated once the stack
 > frame is popped.  in other words, when the function returns, all memory
 > allocated by alloca is freed.  this means no memory leaks.  very cool.
 > 
 > however, in the man page, under BUGS, it says:
 > 
 > BUGS
 >        The alloca function is machine dependent.
 > 
 > this doesn't say anything to me.  what does it mean for a function to be
 > machine dependent?   does it behave differently across different
 > machine architectures?  does code compiled on one x86 machine not run on
 > another x86 machine?
 > 
 > what exactly is the man page warning me about?

Jeff gave the appropriate answer here; however, it's worth pointing
out that alloca() is not standard - either to C or POSIX (or any other
standard to my knowledge); so there's no guarantee you can use it in
other environments. In practice, it is a fairly common UNIX extension,
however.

The latest C standard (C99) has addressed most of the uses which make
alloca() convenient through the use of "compound literals". This
facility allows you to specify a struct or array literal, which is
freed when it goes out of scope. It has been supported (though not
fully) for some time in GCC; you can read about it in GCC's info page,
under C Extensions: Compound Literals.

However, there is only one implementation currently in existence that
supports the C99 standard - and GCC isn't it (still a rather far cry
from compliance, actually). So, using this construct isn't portable
across a variety of other platforms, either. However, there is at
least the fact that it is in the C standard, and will be implemented
in all modern C implementations at some time in the near future -
alloca() still shows no signs of standardization (e.g., it's not in
the current POSIX draft).

For my part, I don't use either one, until more conformant C99
implementations are abundant.

If you're curious, the one conformant C99 implementation is available
on Linux. It is not Free, however - either as in beer or speech. I
don't own it, but have a good deal of respect for the developer, and
have often considered it. Also, the web site gives you a free trial
run of their software - only checks for syntax errors, though: it
won't actually compile or run software.

-Micah