alloca() for TurboC

Sidney Markowitz sidney at saturn.ucsc.edu
Thu Aug 23 09:57:48 AEST 1990


trier at po.CWRU.Edu writes:
>Here's a version of alloca I use.  It's my clone of a version from some
>piece of PD software I saw a year or two ago.

[For anyone who still hasn't gotten the idea, alloca is supposed to
allocate storage (like malloc) which is automatically freed upon exit
from the calling procedure (as if they are on the stack like local
variables).]

I haven't checked it out thoroughly in TC 2.0, but in TC++ nothing
that actually puts the alloca'd storage on the stack is going to work.
For one thing, the compiler may save a value on the stack before the
call to alloca, then try to pop it after the call, not realizing that
alloca has changed the stack. Also, if you look at the assembler code
generated for a function that has 0, 1 or 2 words of local variables,
you will see that no stack space is reserved for them (SI and DI
registers are used instead) and the compiler assumes that it doesn't
need a mov sp,bp instruction to restore the stack on exit. This
assumption is not true if alloca has pushed stuff on the stack
expecting it to be cleaned up on exit. Basically, you can't have a
real alloca without support from the compiler.

There's a portable alloca written in C that I've seen with some FSF
software. It simulates the effect of alloca by calling malloc and
maintaining a linked list of pointers to the allocated blocks, along
with the value of SP at the time of each allocation. Whenever alloca
is called, it goes through the linked list, freeing all blocks for
which the saved SP is smaller (deeper in the stack) than the current
one. So alloca'd storage is not freed at once upon exit from the
routine that is calling alloca, but instead is freed approximately the
next time alloca is called.

If there is interest, I can post the code. But I suggest rewriting the
program to use malloc and free instead of alloca.

-- sidney markowitz <sidney at saturn.ucsc.edu>



More information about the Comp.lang.c mailing list