Clang -Wunsafe-buffer-usage tips
Clang C++ flag
-Wunsafe-buffer-usage
enables a heuristic that can catch potentially unsafe buffer access.
However, this flag is
known
to make warnings that are unavoidable, such as accessing elements of
argv
beyond argv[0]
, even via encapsulation such as
std::span.
This flag could be used by occasionally having a human (or suitably trained AI) occasionally review the warnings. For example, in CMake:
option(warn_dev "Enable warnings that may have false positives" OFF)
if(warn_dev)
add_compile_options("$<$<COMPILE_LANG_AND_ID:CXX,AppleClang,Clang,IntelLLVM>:-Wunsafe-buffer-usage>")
endif()
argv general issues
General issues with argv
are discussed in C++ proposal
P3474R0
std::arguments
.
An
LLVM issue
proposed an interim solution roughly like the following, but at the time of writing, this still makes a warning with -Wunsafe-buffer-usage
.
#if __has_include(<span>)
#include <span>
#endif
#if defined(__cpp_lib_span)
# if __cpp_lib_span >= 202311L
# define HAVE_SPAN_AT
# endif
#endif
int main(int argc, char* argv[]) {
#ifdef HAVE_SPAN_AT
const std::span<char*> ARGS(argv, argc);
#endif
int n = 1000;
if(argc > 1) {
n = std::stoi(
#ifdef HAVE_SPAN_AT
ARGS.at(1)
#else
argv[1]
#endif
);
}
return 0;
}