Reputation: 2097
I have a line of code in my program:
float cache[featureHeight-1];
where featureHeight is a function parameter. Now when the C compiler translates this to assembly, how does it know how much stack space to allocate, since featureHeight is undetermined at compile time? Or does the compiler convert this to a malloc call behind the scenes?
(C99 btw, no compiler errors or warnings, and code runs perfectly)
Upvotes: 4
Views: 162
Reputation: 65116
There's no need to know the amount of space to reserve on the stack in advance.
On many architectures reserving space on the stack just involves subtracting a value (any value - no need to be static) from the stack pointer and then using that as a pointer to the value. So there is some runtime calculation going on, but nothing as complicated as a malloc. These are of course just implementation details (the C standard probably doesn't talk about stack pointers), but this is how it works in practice.
Some platforms even have a non-standard function such as alloca that does the same except via a function call.
Upvotes: 3
Reputation: 262464
C99 does have the ability to get dynamically sized automatic (stack-allocated) arrays.
So your method's stack frame will not be fixed, but sized in order to fit your array.
Upvotes: 2
Reputation: 224844
Not a malloc call, usually, though I guess that would be possible. It simply reserves the necessary space on the stack and uses that. this feature is called a "variable length array" and was introduced in C99. Its semantics are identical to those of a normal compile-time array, except that they're sized/allocated at runtime.
As far as the lower-level/assembly language side of things goes, a multiplication of featureHeight-1
By sizeof(float)
and a decrement of the stack pointer would be all that's required. Watch out for stack overflows!
Upvotes: 4