I have this following code and I don't really understand which variable parts in the test_function are stored onto the stack segment?
In the book it says "The memory for these variables is in the stack segment", so I presume it is when the variables are actually initialized to a value. Right?
void test_function(int a, int b, int c, int d) {
int flag; //is it this
char buffer[10];// and this
//or
flag = 31337; //this and
buffer[0] = 'A'; //this. Or all of it?
}
int main() {
test_function(1, 2, 3, 4);
}
The various C standards do not refer to a stack, what it does talk about is storage duration of which there are three kinds(static, automatic, and allocated). In this case
flag
andbuffer
have automatic storage duration. On the most common systems objects that have automatic storage duration will be allocated on the stack but you can not assume that universally.The lifetime of automatic objects starts when you enter the scope and ends when you leave the scope in this case your scope would be the entire function
test_function
. So assuming there is a stack thenbuffer
andflag
in most situations that I have seen there will be space allocated on the stack for the objects when you enter the function, this is assuming no optimization of any sort.Objects with automatic storage duration are not initialized explicitly so you can not determine their initial values you need to assign to them first.
For completeness sake, the various storage durations are covered in the C99 draft standard section
6.2.4
Storage durations of objects paragraph 1 says(emphasis mine):Lifetime for automatic objects is covered paragraph 5 which says :
flag
,buffer
, anda,b,c,d
will be on the stack (well compiler may just remove all the code and call it dead code since it's unused).