0
while(true)
{
   char array[1024] = {0};
   ....
   .....

}

I just want to know does stack over flow can happen in the above strip of code, or does the stack unwinds in every loop. Thanks in advance.

3
  • Does your while loop has only char array[]? or does it have any other variables? Commented Jul 6, 2016 at 7:20
  • It has only a character array Commented Jul 6, 2016 at 7:24
  • No problem as far array has fixed size. VLA is a different story. Commented Jul 6, 2016 at 7:29

2 Answers 2

3

The lifetime of an object with automatic storage duration is the block in which it was defined. The block in this case starts at the beginning of the while loop and ends at the end of it. So theoretically the object is reallocated every time we enter the loop.

In practice though, the compiler will just allocate enough space on the stack before the loop or even at the beginning of the function and just use that each time.

No chance of stack overflow.

Sign up to request clarification or add additional context in comments.

Comments

2

The scope of array is limited to a particular iteration of the loop.

So yes, conceptually, a new array is created on each iteration, although a good compiler may well optimise this out if there are no side effects.

Whatever happens, there's no danger of a stack overflow error due to the repeated declaration and initialisation of array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.