If i have a for loop:
for (uint8_t x = 0; x < 100; x) {
char f[2000] = {0,};
}
what actually is going on here? Is this reusing the same memory address everytime so it only actually allocates it once, or is it using a new memory location each loop? Does it depend on optimization levels? What about the implementation?
CodePudding user response:
There is no guarantee that f
is allocated in the same memory address every time around the loop, but it should be very hard to find a compiler that doesn't do it that way. I have seen f
get trashed in the loop iteration, so yes it really does go out of scope at the closing brace.
A modern compiler will almost always gather up all the variable declarations within a function, analyze for overlapping runtime scope (not compile time--It's smart enough now to figure out when a variable isn't used any further down in the function most of the time), and allocate all the fixed* memory on the stack at function entry time. This runtime call is still much cheaper than malloc()
.
Stack allocation is done with a single instruction for all the variables: sub rbp, constant
. Freeing the memory is done the same way: add rbp, constant
. This buffer is almost half the size (4KB) where the compiler has to emit a call to the runtime to verify the stack has enough room. On Windows, this function is called _chkstk
.
*Flexible arrays are allocated with a stretchy stack element near their first use.
CodePudding user response:
When one iteration of the loop ends and a new one begins, the lifetime of the array f
ends and the lifetime of a new array f
starts. As far as the C standard is concerned, each is distinct from the other.
In practice, the compiler may use the same memory address for each iteration of f
or it might not. This is not something that can be depended on. Certain optimizations may take advantage of the fact that the lifetime of f
ends at the end of the loop body and do things that appear strange in non-compliant code.
In short, stick with what the C standard says is valid and don't make any assumptions about f
.