Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!rutgers!umd5!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: How are local vars allocated? Message-ID: <9367@mimsy.UUCP> Date: Sat, 14-Nov-87 19:46:37 EST Article-I.D.: mimsy.9367 Posted: Sat Nov 14 19:46:37 1987 Date-Received: Sun, 15-Nov-87 20:30:55 EST References: <189@dalcsug.UUCP> <7401@prls.UUCP> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 61 In article <7401@prls.UUCP> gardner@prls.UUCP (Robert Gardner) writes: >Is there any danger of stack overflow with the following construct: >for(;;) { > int k; > etc. etc. >} No. >In other words, is k allocated only once at the beginning of the >procedure containing this construct, or is it allocated each time >the {} block is entered? Is the answer implementation dependent? The answer is implementation dependent, but if a loop like for (;;) { int k; } runs for several minutes, then produces a stack overflow, the implementation is horrible. For example, a very straightforward compiler might generate this: proc() { int a, b; for (;;) { int k; if (g()) break; } a = 1; } -------- _proc: sub $8,sp | create local variables a, b L1: sub $4,sp | create local variable k call _g | run g tst r0 | what was g's return value? bne L3 | nonzero, break loop L2: add $4,sp | destroy local variable k bra L1 | back around the loop L3: add $4,sp | destroy local variable k mov $1,-4(sp) | a = 1 L0: add $8,sp | destroy locals a, b ret Label `L2' above is for a `continue' that might appear inside the for loop. It is not used, but so what? Likewise, L0 is allocated at the beginning of code generation for proc(), in case there are any `return' statements in it. I optimised away the sequence a truly dumb compiler would probably emit for `if (g()) break'. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris