Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Did I find a bug in CppCheck? Why do I get the "Null pointer dereference" error here?

I'm using Cppcheck to manage my code. I have the following function:

bool my_function(std::string my_string) const
{
 return 0 == my_string.compare("Some text");  // line 3
}

To my surprise, I get the Null pointer dereference in the line 3.

I am completely confused: there are no pointers in my function. Why do I get this error?

I've tried to investigate it:

  1. I checked if the string my_string is empty.

  2. I created an object using "My text" to make sure that Cppcheck doesn't complain about using a temporary object:

    bool my_function(std::string my_string) const
    { 
     std::string str("Some text");
     return 0 == my_string.compare(str);  // line 3
    }
    

What else can I do? Is is a bug in Cppcheck? Is there a problem with the compare function itself? I'd be surprised if this was the case, since cppcheck doesn't complain about any other std functions that are used in my project.

Note: I'm not asking about the possible Null pointer dereference error, so this is not a duplicate of any of the following questions: 1, 2 or 3.

like image 204
user2738748 Avatar asked Jun 14 '16 15:06

user2738748


People also ask

What is the problem with dereferencing the null pointer?

Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.

What is dereference before null check?

June 01, 2022. CWE-476 Null Pointer Dereference is a programming error that can occur when a program attempts to deference a null pointer. This can happen when the programmer mistakenly assumes that a pointer pointing to NULL is actually pointing to a valid object.


1 Answers

I am a Cppcheck developer.

It looks like a bug in Cppcheck. However I fail to reproduce this false positive. If you don't use latest Cppcheck please update. Otherwise please report this in the cppcheck bug tracker: http://trac.cppcheck.net

like image 79
Daniel Marjamäki Avatar answered Sep 27 '22 20:09

Daniel Marjamäki