ITADN

Questions about MISRA static analysis

#1298OpenLonely-Dream 创建于 2026-02-25
L
Lonely-Dreamcommented
First of all, I would like to thank the author for their contribution. The static analysis tool reported that the `get_environment_value` function violated MISRACPP2023-25_5_2-a-1 rule. https://github.com/CLIUtils/CLI11/blob/fe3772d3c2969330ed0e4f32351ad066e8d375c5/include/CLI/impl/StringTools_inl.hpp#L576-L595 **The pointers returned by the Standard Library functions 'localeconv', 'getenv', 'setlocale' or, 'strerror' shall only be used as if they have pointer to const-qualified type [MISRACPP2023-25_5_2-a]** This rule is the highest level. In the glibc library of Linux/Unix systems, getenv returns a pointer to the global environment. Although `get_environment_value` does not modify this pointer, it is still recommended to use const to qualify it. I tested this implementation and the tool no longer reports this problem. ```c++ std::string get_environment_value(const std::string &env_name) { std::string ename_string; #ifdef _MSC_VER // Windows version char* buffer = nullptr; std::size_t sz = 0; if(_dupenv_s(&buffer, &sz, env_name.c_str()) == 0 && buffer != nullptr) { ename_string = std::string(buffer); free(buffer); } #else // This also works on Windows, but gives a warning const char* buffer = nullptr; buffer = std::getenv(env_name.c_str()); if(buffer != nullptr) { ename_string = std::string(buffer); } #endif return ename_string; } ``` If you'd like, I'll submit a PR.
0 条评论