Re: variable allocated from stack/bss ??
- From: websnarf@xxxxxxxxx
- Date: 29 Nov 2006 13:09:34 -0800
onkar wrote:
Given the following code & variable i .
int main(int argc,char **argv) {
int i;
printf("%d\n",i);
return 0;
}
here i is allocated from bss or stack ?
I think it is stack,because it prints garbage value; If it were
allocated from bss the default value would be 0
please tell me if I am right or wrong ??
Well, from a storage point of view, the standard calls these static and
auto respectively instead of bss or stack. (These latter two are
usually the names of segments commonly given by some platforms and they
implement these two kinds of storage.)
Basically, auto variables are anything declared inside the scope of a
function without a static decorator, and correspond to your
implementation's "stack". An auto variable that is not autoinitialized
may have arbitrary contents until it is assigned a value (things are
more complicated with structs and unions, but they behave exactly as
you would expect). Everything else one way or another ends up in some
kind of static memory and as you suspect will have a default
initialization to 0. (There is a little confusion here, since static
and globals have different semantic meaning, but have the same storage
properties. Let's ignore this for now and just consider globals to be
statics with extra scope.)
Using the name "stack" is a bit misleading since the stack that can be
inferred from the standard is, in fact, the call-stack. Many
implementations will mix in auto data in their implementations of the
call-stack and call the whole thing just the stack. But it is not
necessary for implements to do things this way (and in fact doing this
commonly leads to security problems related to imprecise usage of the
standard C library.)
Probably only the most cynical or the ignorant would be unaware of what
you mean by bss, but again this is technically a platform-specific
name. The heap, and some static storage, for example, may in fact be
found in entirely different segments as a matter of convenience to the
compiler as they are with WATCOM C/C++ and MSVC++. (Note that the heap
is not pre-initialized to 0 either, but it is certainly not
auto-storage.)
In your example the variable i is an auto. That doesn't necessarily
mean its on any particular implementation's stack -- it just behaves as
if it were. The reality is that auto variables are commonly mapped to
machine registers, and in the case you show, it is very likely that
that is where i ends up.
--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
.
- References:
- variable allocated from stack/bss ??
- From: onkar
- variable allocated from stack/bss ??
- Prev by Date: Re: Casting malloc
- Next by Date: Re: Casting malloc
- Previous by thread: Re: variable allocated from stack/bss ??
- Next by thread: Re: variable allocated from stack/bss ??
- Index(es):
Relevant Pages
|