[comp.lang.c] Alloca for Turbo C

ressler@cello.cs.cornell.edu (Gene Ressler) (01/30/91)

GNUish MSDOS code (extremely useful stuff) 
often compiles nicely under Turbo C
(though the port was apparently done for MS-C), except it
frequently uses alloca(), which is supposed to get
new memory in the current stack frame.  The memory
is supposed to be automatically freed when the current
 { ... } block (or at least the current function call)
closes.  So far I've been able to get bison and flex (GNU's
yacc and lex) to compile by faking alloca() with malloc(), but
it's a pain to ensure that free() is called correctly, and of
course free() is time-consuming in an inner loop because it has
to merge free blocks, etc.

The question is whether I can get away with writing my own
alloca().  Allocation seems pretty easy.  SP points to the last
loc in use on the stack, so (without checking for alignment,
overflow, etc.) we can get _cdecl near void *alloca(unsigned n)
with something like:

alloca	proc near
	pop bx			; get return address
	pop cx			; get n
	sub sp,cx 		; allocate space on stack
	mov ax, sp		; set up return pointer
	sub sp, 2		; compensate for caller's increment
	jmp bx			; return
alloca 	endp

The problem is with deallocation.  WILL IT ALWAYS BE DONE BY
CODE GENERATED BY TC?  Things are fine with the `normal' activation
protocol: push bp; mov bp,sp; sub sp,?  ...  mov sp,bp; pop bp; ret
A possible bad case is if Standard Stack Frame is Off.  Then this
protocol can be skipped entirely and mucking with SP is disaster.
I'm asking those who are really familiar with the TC's code generator 
if they know of other dangers e.g. functions with no locals,
tail calls, nested blocks with locals, and so on.  Of course a
working alloca() would be even better (-8 .

Gene Ressler