In
void diagonalize(unsigned long long int array_size) {
lapack_complex_double z[array_size];
}
z
is variable-length array (VLA) feature from C99, C++ standard doesn't have it, but some C++ compilers support it as an extension for built-in types.
The default stack size is around 8MB on Linux, so using unsigned long long int
for array_size
is an overkill, unsigned
would suffice.
Notably, Linux kernel got rid of all VLAs in 2018 because it can underflow/overflow the stack and corrupt it and hence provide vectors of attacks for kernel exploits.
Whether it underflows the stack depends on how much stack space is available when the function is called and that depends on the current call chain. In one call chain there can be a lot of stack space, in another - not so much. Which makes it hard to guarantee or prove that the function always has enough stack space for the VLA. Not using VLAs eliminates these opportunities to underflow/overflow the stack and corrupt it, which are the most popular and easy avenues for exploits.
would the array be allocated and deallocated for each value of array_size
, or would only one array be used and overwritten during the program?
It is an automatic function local variable allocated in the function stack on each call. The allocation reserves the stack space and it normally takes one CPU instruction, like sub rsp, vla-size-in-bytes
on x86-64. When a function returns all its automatic function variables cease to exist.
See https://en.cppreference.com/w/cpp/language/storage_duration, automatic storage duration for full details.
Would it just be better to make three separate diagonalize functions which each internally declare an array with the size given by a unique global constant?
It would make no difference because all automatic variables are destroyed and cease to exist when a function returns.