开发者

No Stackoverflow: auto object inside while loop

I was going through someone's code where I came across a thread:

while(TRUE)

{
 ......
 STRUCT_MSG_SYS_HEADER  sysHdr;
 .....
 ....
}

There are five threads like this, My point is that "STRUCT_MSG_SYS_HEADER sysHdr;" will lead to stackoverflow after some time or days... (Not tested though). So I decided to write a simple sample application

  1 #include "stdio.h"
  2
  3 struct infinite
  4 {
  5     int arr[1000000];
  6 }infinite;
  7
  8 int main()
  9 {
 10     while(1)
 11     {
 12         struct infinite infobj;
 13         printf("\ninfinite = %x\n", &infobj);
 14     }
 15     return 0;
 16 }

But here it is printing the same address for infobj. Is my thinking of stackoverflow is wrong or here compiler has do开发者_运维知识库ne some optimization? (I consider myself good coder, but things like these force me to think again, read dennis richie again)


The infobj is destroyed at the end of each iteration of while loop, hence stack is not overflowing and you are getting the same address again and again. Whether you can allocate int arr[1000000] on the stack depends on the maximum allowed stack size per thread. On VC compiler this is 1 MB but can be changed through compiler options.


No stack overflow will occur. That stack-allocated variable will only live for the duration of the loop iteration and after that stack space it occupies can be reused. Typically when the next iteration starts exactly the same space will be used for the variable in the new iteration.

Stack overflow could occur in case of deep recursive chain of calls of the same function because when the new call would start all the variables in the scope of the previous call would need to be retained, so the sapce would not be reused, but instead more stack space would be used for each new call. This is not the case in this question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜