Search code examples
cstack-overflow

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 done some optimization? (I consider myself good coder, but things like these force me to think again, read dennis richie again)


Solution

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