Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the C compiler know how big to make the array?

Tags:

c

c99

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)

like image 350
user1299784 Avatar asked Jan 10 '23 10:01

user1299784


2 Answers

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!

like image 82
Carl Norum Avatar answered Jan 18 '23 07:01

Carl Norum


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.

like image 25
Matti Virkkunen Avatar answered Jan 18 '23 08:01

Matti Virkkunen