which variable parts are stored to the stack in this code?

情到浓时终转凉″ 提交于 2020-01-24 22:55:30

问题


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

回答1:


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).




回答2:


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.[...]



来源:https://stackoverflow.com/questions/18834568/which-variable-parts-are-stored-to-the-stack-in-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!