which variable parts are stored to the stack in th

2019-08-13 09:06发布

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);
}

2条回答
Rolldiameter
2楼-- · 2019-08-13 09:18

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 and buffer 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 then buffer and flag 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):

An object has a storage duration that determines its lifetime. There are three storage durations: static, automatic, and allocated. Allocated storage is described in 7.20.3.

Lifetime for automatic objects is covered paragraph 5 which says :

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.[...]

查看更多
趁早两清
3楼-- · 2019-08-13 09:31

flag, buffer, and a,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).

查看更多
登录 后发表回答