Andre said:
Hi,
If I say:
int i = 5;
Does 'i' get stored on the stack?
There isn't necessarily a "the stack". On typical implementations, the
answer to your question is "it depends" - if the line was at file scope,
it would usually be stored in an initialised data segment, but if it's
at block scope, it would be stored on an argument stack (or something
that behaves like an argument stack, from the point of view of a C
program - that is, each recusive invocation of a function creates a new
instance of the object, disjoint from the existing instances of that
object, and as the functions return, the objects are deallocated in
reverse order).
None of this matters for writing portable C programs though - all that
matters, from the C point of view, is the lifetime of the object. There
are three possible object lifetimes in C - static storage duration,
which applies to file-scope objects and block-scope objects declared
with the static keyword; automatic storage duration, which applies to
all other objects declared at block scope; and dynamic storage duration,
which applies to objects created with malloc(), calloc() or realloc().
Static storage duration means the object lives for as long as the
program does. Automatic storage duration means the object is created
when the program begins executing the block it's declared in, and ceases
existing when the end of the block is reached. Dynamic storage duration
means the object is created at the time of themalloc()/calloc()/realloc()
call, and ceases to exist at the time of the corresponding free().
If yes, where *is* the stack? On the heap?
Probably not, because a stack needs to be in contiguous memory.
Typically this is solved by having the heap grow upwards from the bottom
of memory, and the stack grow downwards from the top.
What manages the stack and how does it get created? Thanks
Code your compiler creates as part of the process of compiling your
program - sometimes with help from special CPU instructions, sometimes
not.
- Kevin.