doing nasty things with internal static variables

Dan Mercer mercer at npdiss1.StPaul.NCR.COM
Thu Mar 21 06:52:17 AEST 1991


In article <1991Mar19.183920.18911 at rice.edu> fontenot at 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 at comet.rice.edu)


-- 
Dan Mercer
NCR Network Products Division      -        Network Integration Services
Reply-To: mercer at npdiss1.StPaul.NCR.COM (Dan Mercer)
"MAN - the ultimate one word oxymoron in the English Language"



More information about the Comp.lang.c mailing list