how memory is allocated on Stack

Suppose if i code like this,

1
2
3
4
5
6
while( true )
{
    int x;
    // do some thing;
    // break on some condition match;
}


whether memory is allocated for ints x one time or each time it hits int x.

Thanks,
I'd imagine it'd be allocated each time. At the end of the loop, the int goes out of scope and is destroyed.
I haven't read the standard about this, but it is possible that the variable exists on the stack outside of the local scope. What is required is appropriate construction and destruction when program flow hits block boundaries.

That is, the compiler can do things that you don't/shouldn't know about from the language's/programmer's point of view.

From our POV, x only exists once program flow crosses its declaration inside the while loop.

Hope this helps.
Stack memory is typically allocated "up front"

And by "allocated" I just mean "the stack pointer is moved".

So the memory will only be allocated once on entry to the function, and deallcoated when the function exits. Also note that allocation is trivial because it doesn't have to actually allocate memory, it just consumes stack space which has already been allocated.



HOWEVER, a variable inside a loop body will be constructed and destructed every time the loop runs. For a type like int this doesn't mean anything because it's a built-it type and has no ctor/dtor... bur for a complex type like string where the ctor/dtor is nontrivial and may require additional allocation.... this could be very, very wasteful.
Stack memory is typically allocated "up front"
...but not necessarily. The stack pointer could be updated at the block level too...

Again, I don't know enough to say whether any compiler does this or not, but it is possible.
Yes you're right. That is certainly possible.

But, really, the key point here is that no allocation is actually taking place. The memory has already been allocated (except in infrequent cases where the stack needs to be resized)
Topic archived. No new replies allowed.