C/C++ Stack Usage Compilation Warning and Error
Introduction
In my previous blog post “Large Array Safety Issue”, I discussed the catastrophic consequence of using large arrays in a safety system. In addition to large arrays, technically, there can also be a single object that is too large and unsafe to be put on the stack during the runtime. More importantly, those unsafe implementations might be in some black box functions that we have to use but got no interest or time to read or check. So the questions becomes, how could we identify large stack usages quickly and prevent it as much as possible.
In this blog post, I would like to quickly discuss throwing compilation warning and error for large C/C++ stack usages.
GCC Large Stack Usage and Error
Similar to the examples that I presented in the previous blog post “Large Array Safety Issue”, the functions in the following example are using large static arrays, allocating dynamic memory, and using variable length arrays (dynamic arrays) on stack, respectively.
1 |
|
GCC allows us to throw warnings for the functions that has large stack usages over certain threshold using -Wstack-usage=byte-size
. It will also throw warnings for stack usages that are dynamic and unbounded via operations such as alloca
or variable-length array. (alloca
or variable-length array are really bad practices and should be avoided as much as possible.)
1 | $ g++ large_stack.cpp -o large_stack -std=c++14 -Wstack-usage=204800 |
However, -Wstack-usage=byte-size
only enables throwing warning at compile time. If the user did not pay enough attention to the compilation logs, those warnings would be missed and the unsafe build would still be used for production.
Therefore, we would like to throw errors instead of warnings at compile time for unsafe stack usages. In our case, we could do it using -Werror=stack-usage=byte-size
and the build would be failed.
1 | $ g++ large_stack.cpp -o large_stack -std=c++14 -Wstack-usage=204800 -Werror=stack-usage=204800 |
References
C/C++ Stack Usage Compilation Warning and Error
https://leimao.github.io/blog/C-CPP-Stack-Usage-Compilation-Warning-Error/