[vox-tech] C question: global vs local const

Mark K. Kim vox-tech@lists.lugod.org
Thu, 17 Jan 2002 21:17:37 -0800 (PST)


On Thu, 17 Jan 2002, Peter Jay Salzman wrote:

> begin Mark K. Kim <markslist@cbreak.org>
> > You're initializing K with a variable.  Because globals are calculated at
> > compile time,

Since Jeff will sooner or later jump in to correct me, I'll correct myself
before that happens:

I didn't meant to say that globals are calculated at compile time -- they
can certainly be modified during runtime.  What I meant was that initial
values of globals have to be calculated at compiletime -- due to the way
they are stored in memory.

Local variables will also be calculated as much as possible during
compilation (like all the literals will be precalculated), if you have a
decent compiler.

> > and const variables are overwritable
> > under certain architectures by indirectly dereferencing it (but not on x86
> > Linux).

When I wrote this, I was actually thinking of literals.  On some
systems, you can silently write over literals, like this:

   int main(void)
   {
      char* s = "Hello";
      *s = 'J';

      printf("%s\n", s);
      return 0;
   }

On Linux, it won't let you do that, but on SGI (O2?) it very smoothly lets
you overwrite the literal.  This is normally not a problem (besides the
bad style), unless the literal space (often stored in the code space) is
shared between processes...  Then it becomes a security risk.

You *can* overwrite non-global const variables under x86 Linux...
apparently :)  It makes sense, since they go on the stack (turning one or
two words on the stack into read-only memory is inefficient from the
hardware standpoint).  It segfaults if you try to overwrite global
constant or static constants, though (global constants are pretty much
like literals, and static variables are pretty much like globals...)

> thanks mark!

I apologize for not being as accurate as I should be!

-Mark :)

--
Mark K. Kim
http://www.cbreak.org/mark/
PGP key available upon request.