Re: Confusion between Stack and Data segment



In article <871w8r1f1e.fsf@xxxxxxxxxxxxxxxxx>,
Rainer Weikusat <rweikusat@xxxxxxxxxxx> wrote:

Utkado <utkado@xxxxxxxxx> writes:
I am not clear with my understanding of stack and data segment.
Consider this example

int main()
{
int i;
int j=5;
return 0;
}

Does variable " j " get stored in the data segment as it is
initialized OR is it stored in the stack segment as it is a local
variable.
Does variable " i " get stored in the stack segment or bss
(uninitialized).

The basics are that two (simplification) different storage classes
exist in C, automatic storage and static storage. An object with
automatic storage duration starts to live when the function defining
it is invoked and ceases to exit when it returns. An object with
static storage duration comes into existence at program start and
continues to be a live object until the program terminates.

Both i and j have automatic storage duration, because they are defined
in 'main', consequently, they would usually be stack-allocated.

I suspect the OP is thinking more of something like this:

void foo() {
char *a = "abcdefg";
}

The pointer a is stored in the stack segment, as it's a local variable.
But the string that it points to is stored in the data segment, because
literal strings are static. Actually, some implementations will store
literal strings in the text segment, where the executable code lives,
because literals are not supposed to be modified.

Another case is local variables like:

char a[] = "abcdefg";

In this case, there's an array in the stack segment, and whenever the
functionis entered it's initialized by copying the contents of the
"abcdefg" string into it, i.e. this is equivalent to:

char a[8];
strcpy(a, "abcdefg");

As above, the literal string may live in the data or text segments; in
this case, I suspect almost all implementations will use the text
segment.

In the case of small numbers used to initialize int variables, though,
the initialization is most likely done using immediate data in the
instructions used to fill in the stack frame. But if a function has
lots of initialized local variables, another way to do it would be to
have a template of the stack frame in the text segment, and copy it when
entering the function.

--
Barry Margolin, barmar@xxxxxxxxxxxx
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***
*** PLEASE don't copy me on replies, I'll read them in the group ***
.