Xref: utzoo comp.os.msdos.programmer:620 alt.msdos.programmer:2066 comp.lang.c:31316 Path: utzoo!mnetor!geac!torsqnt!news-server.csri.toronto.edu!cs.utexas.edu!usc!ucsd!ucbvax!agate!darkstar!saturn.ucsc.edu!sidney From: sidney@saturn.ucsc.edu (Sidney Markowitz ) Newsgroups: comp.os.msdos.programmer,alt.msdos.programmer,comp.lang.c Subject: Re: alloca() for TurboC Summary: TAASTAASA (...As A Simple alloca) Keywords: alloca, DOS, TurboC, assembly Message-ID: <6255@darkstar.ucsc.edu> Date: 22 Aug 90 23:57:48 GMT References: <2745@onion.reading.ac.uk> <3860@bingvaxu.cc.binghamton.edu> <1990Aug22.032243.18214@usenet.ins.cwru.edu> Sender: usenet@darkstar.ucsc.edu Followup-To: comp.os.msdos.programmer Organization: University of California, Santa Cruz Lines: 36 trier@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