I wanted to check whether a g++ compiler-flag exists that warns me about nullpointer-dereferencing. When compiling this code with g++ (GCC) 13.1.1
and these compiler flags: -Wnull-dereference, -Wnonnull, still nothing happens. No warning, no error..
#include <iostream>
int main() {
double *elem = new (std::nothrow) double;
elem = nullptr;
std::cout << *elem << '\n';
delete elem;
return 0;
}
So I tried options that control static analysis
: I only came across these two: -Wanalyzer-null-argument, -Wanalyzer-null-dereference (still, no success). Is there really no way of achieving this? Note that I am aware of clang-tidy and other static analysis tools like cpplint, clazy and cppcheck that successfully report these kinds of problems. But I want to rely only on compilation flags.
From the documentation of -Wnull-dereference
:
This option is only active when -fdelete-null-pointer-checks is active, which is enabled by optimizations in most targets. The precision of the warnings depends on the optimization options used.
Enable optimizations (-O1
is enough) and you will get the warning.
-Wnonnull
does something completely different. (Also see documentation link above.)
The -Wanalyzer-*
options only take effect if you enable the static anaylzer with -fanalyzer
and then they are the default. These options are meant to be used in the -Wno-*
form to disable specific static analyzer checks. See documentation as well.