False-Negative for a QT project

Make sure to read this post before raising a thread here:

Then tell us:

  • What language is this for?
    CPP

  • Which rule?
    Null pointers should not be dereferenced (cpp:S2259) and so on

  • Why do you believe it’s a false-positive/false-negative?

  • The context might be null

  • Are you using

    • SonarQube - Enterprise edition 9.8
  • How can we reproduce the problem? Give us a self-contained snippet (best) or screenshot (good)
    CMutexTester.txt (2.3 KB)

Hello, @honghua

void CMutexTester::initialize(CPlugin *plugin, CPluginContext *context)
{
    Q_UNUSED(plugin)

    //  Expectation: sonar prompts you to check that the context pointer is empty before using it
    jobMgr = context->getService<IJobManager>();

    //  Expectation: sonar warns of the risks of null Pointers
    jobMgr->addJob(this);

    testDeadLock();

    writewMapWithAnotherLock();

    testMagicNumber();
}

Indeed, context is not guaranteed to point to anything valid, so it might as well be a nullptr. Strictly speaking, this is a false negative.

Yet, such dereferences (with no prior check for nullptr) are used very often in C and in C++ code. And in the majority of the cases they are safe because they rely on some implicit invariant, for example, “this vector contains only non-null pointers” or “this function is called only with non-null arguments”.

Raising an issue for every dereference will introduce a large amount of noise and will annoy an average developer more than it helps them.

For that reason, we only raise an issue if we have a reason to assume that the pointer might be null. For example, this pointer was checked for nullptr before, or it is assigned a null at some point. Arguably, this is a tradeoff between discovery and precision, and Sonar chooses precision and sacrifices some discovery.

That being said, in some safety-critical applications it might make sense to enforce a stricter version of this rule. I’ve created CPP-4078 to keep track of how often this rule is needed. If the request pops up often, we will consider implementing it.

Let me know if something is not clear.