Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!husc6!mailrus!ames!lll-tis!helios.ee.lbl.gov!pasteur!ucbvax!decwrl!decvax!mcnc!ece-csc!ncrcae!ncr-sd!hp-sdd!hplabs!hpda!hp-sde!hpcea!hpnmd!hpsrli!darrylo From: darrylo@hpsrli.HP.COM (Darryl Okahata) Newsgroups: comp.sources.d Subject: Re: Simulation of 'alloca' -- can it be done in TurboC or MSC? Message-ID: <3100002@hpsrli.HP.COM> Date: 27 May 88 17:05:26 GMT References: <203@lcuxa.UUCP> Organization: HP Network Measurements Div, Santa Rosa, CA Lines: 63 In comp.sources.d, dg@lakart.UUCP (David Goodenough) writes: > From article <203@lcuxa.UUCP>, by mike2@lcuxa.UUCP (M S Slomin): > > Quick question: has anyone worked out a way to simulate the 'alloca' > > function in either TurboC or MSC (DOS for those who don't know)? > > Write it in assembler. I don't know how to do alloca in C in a portable [ ... ] > .extern _alloca > _alloca: > pop de > pop hl > call #neg ; negate argument > add hl,sp ; allocate the space > push hl > push de ; put args back so return works > ret ; home we go - hl points to space. > > This should be fairly easy to convert to 8086 assembler (What, your C compiler > can't talk in assembler?? :-) Different segments may be a pain - this space [ ... ] Whoa, it's not as easy as it seems. Take the following code fragment, for example: foo(a) int a; { char *here; here = NULL; if (a == 17) { char *there; there = alloca(SOME_NUMBER); bar(there); here = there; } blech(here); } The problem in the above code fragment is that the stack frame allocated at the start of the if statement block is deallocated at the end of the block. If the above Z80 code was translated into 80x8x code (taking care to move the stack pointer BELOW the allocated area because of interrupts), that code will not work for the above code fragment. Why? Because, at the end of the if block, code will be generated to reset the stack pointer to the value it had at the beginning of the if block (and, chances are, if a simple ADD SP,n is used, the system will eventually crash because the stack pointer was modified by alloca() and is not where it should be). > dg@lakart.UUCP - David Goodenough +---+ > | +-+-+ > ....... !harvard!adelie!cfisun!lakart!dg +-+-+ | > +---+ -- Darryl Okahata {hplabs!hpccc!, hpfcla!} hpsrla!darrylo CompuServe: 75206,3074 Disclaimer: the above is the author's personal opinion and is not the opinion or policy of his employer or of the little green men that have been following him all day.