I expected that stack memory of scope-local variables is reused once they left the scope. This is true for GCC and MSVC, at least in optimised builds. In debug builds they don't reuse stack memory, I guess to be able to poison that memory and catch bugs.
But this is not true for Clang. E.g. the following code outputs different addresses:
#include <stdio.h>
int main()
{
{
int j;
printf("%p\n", &j);
}
{
int j;
printf("%p\n", &j);
}
/*
for (int i = 0; i != 2; ++i)
{
int j;
printf("&j = %p\n", &j);
}
*/
}
The same result (no reusage) if I replace int j;
by int j[1];
.
Interestingly, in cases where such behaviour has higher probability of overflowing the stack, e.g. if an array contains more than one element, its stack space is reused by Clang. Same for for
loops (commented part of the code above).
It seems Clang does this deliberately. Why?