Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does even a single g++ flag warn about nullpointer dereferencing?

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>

auto main([[maybe_unused]] int argc, [[maybe_unused]] char ** argv) -> int {

  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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading