1

I would like to know how is the run-time stack handled when running the code below

   int i;
   for (i = 0; i < 100; i++) {
        int v[i+1];
        ...
   }

Stack is reduced and grown after every loop ? Stack is initially allocated by an amount which will fit v[101] ? Is it optimized by compiler so it treats v as a pointer and do only heap allocations ?

Thanks.

6
  • This is not allowed in C++, so should be tagged only C. Commented Apr 26, 2014 at 23:49
  • @EOF int v[i+1]; is a VLA declaration. Commented Apr 26, 2014 at 23:55
  • @EOF I don't know (probably just for the sake of the question). But your comment didn't make sense in regard to the code. Commented Apr 27, 2014 at 0:01
  • @EOF The question makes sense to me, I don't know what your issue is, or why you are arguing. Commented Apr 27, 2014 at 0:03
  • I just wanted to know how memory is managed in this case. I don't know exactly what it is doing. Eg. Does every loop the address for v[0] is the same ? Commented Apr 27, 2014 at 0:26

1 Answer 1

1

Depends on the compiler and optimization settings. A clever compiler could figure out that the biggest size needed is 100, and allocate that once from the stack at the beginning and reuse it. Stack allocation is practically free as it's just a pointer adjustment so it wouldn't make any sense to use the heap instead.

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

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.