edufgf
edufgf

Reputation: 45

Run-time stack size allocated in dynamic array inside a loop

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.

Upvotes: 1

Views: 106

Answers (1)

Jester
Jester

Reputation: 58762

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.

Upvotes: 1

Related Questions