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)
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With