[Gllug] data segment vs stack

Richard Jones rich at annexia.org
Tue Feb 14 15:15:35 UTC 2006


On Tue, Feb 14, 2006 at 11:10:58AM +0000, t.clarke wrote:
> Apologies if this question seems silly,  but I am just curious as to whether
> the variables declared in the 'main()' function of a C program are created
> in the program's stack (in the same manner as variables declared in any
> 'subsidiary' functions), or in the data segment  (which is where I assume
> 'global' variables are created?)

The answer is, as others have said, on the stack.

Exception#1a: If they are declared 'static', in which case they are
allocated in the initialized data area or bss[1] (which is what you're
calling the "data segment").

Exception#1b: Strings are usually stored in the text[2] segment, which
is read-only, which is why you can't modify them.  Some other
"initializer" data is also kept in the text segment, and copied onto
the stack each time the function is entered, eg:

  f ()
  {
    int a[50] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
    // ..
  }

If you compile the above code with gcc -S and look at the generated
assembler, you'll see a call to memcpy.

Exception#2: The compiler might well decide to allocate them to
registers, in which case they're not in memory at all.  Usually the
compiler will also reserve a slot for them on the stack too, but not
always.  GCC can even put structures in registers, so don't think it's
just simple ints, either.

In older compilers you could tell the compiler which variables you
wanted to keep in registers by using the 'register' keyword, but all
modern compilers ignore this now.

Rich.

[1] http://en.wikipedia.org/wiki/Block_Started_by_Symbol
[2] The name "text" refers to code and read-only data.

-- 
Richard Jones, CTO Merjis Ltd.
Merjis - web marketing and technology - http://merjis.com
Team Notepad - intranets and extranets for business - http://team-notepad.com
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list