Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!samsung!uunet!ncrcom!ncrlnk!ncrstp!npdiss1!mercer From: mercer@npdiss1.StPaul.NCR.COM (Dan Mercer) Newsgroups: comp.lang.c Subject: Re: doing nasty things with internal static variables Keywords: C, crossreference Message-ID: <935@npdiss1.StPaul.NCR.COM> Date: 20 Mar 91 20:52:17 GMT References: <1991Mar19.164037.7421@intellistor.com> <1991Mar19.183920.18911@rice.edu> Reply-To: mercer@npdiss1.StPaul.NCR.COM (Dan Mercer) Distribution: usa Organization: StPaul Lines: 47 In article <1991Mar19.183920.18911@rice.edu> fontenot@comet.rice.edu (Dwayne Jacques Fontenot) writes: :Hello, : :I have found myself doing this because it works, but I am curious if it :is a common practice or if it is highly likely to get me into trouble: : :char *foo() :{ : static char string[64]; : : ... : return(string); :} : :I am concerned about this because though I know that that static variable :is guaranteed to always be there for the function containing it, it is :not really guaranteed to be there (in memory) at any other time :(correct me if I'm wrong). : You are wrong. There, I corrected you. Seriously, there are, in general, three places to keep variable data - the stack, the heap, and the static data area. Automatic variable data is kept on the stack. It will always be there while you remain in the function, but is lost when the function exits and the stack is returned. It is lost, not destroyed. Many a fine bug has occurred because someone returned the address of an automatic variable which is still correct and accessible until some other function is called and uses the stack area. You use malloc to access the heap. The static data area contains your constant data, static data, and global data. The only real difference (in the box) between static and global data is that the linker knows how to access the global data. :I have used this on ANSI compilers on diverse architectures with no problems :yet, and it's just so damned *convenient*. : :Thank you for your time, :Dwayne Fontenot (fontenot@comet.rice.edu) -- Dan Mercer NCR Network Products Division - Network Integration Services Reply-To: mercer@npdiss1.StPaul.NCR.COM (Dan Mercer) "MAN - the ultimate one word oxymoron in the English Language"