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

1

10

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.

Corpuz answered 14/6, 2016 at 15:28 Comment(10)
Looks like a bug to me. I see nothing wrong with the code.Archipelago
did you try return (0 == my_string.compare("Some text"));? Just maybeTrevortrevorr
Just to be clear, the code works without crashing but its just that cppcheck is reporting error, right ?Murphree
@FirstStep, I just tried that and it works now, thanks! But why? The change you suggested shouldn't have any impact on the code. Does it?Corpuz
@Arunmu, yes, that's right.Corpuz
Eventually it does have an impact on the code. And I don't know why still, let me know when you know!Trevortrevorr
I would say it is a false positive for cppcheck. It is not really a bug since as in any static analysis tool false positive are always possible, even if [cppcheck] goal is to detect only real errors in the code (i.e. have zero false positives) (from cppcheck page). But you could signal it (with the parentheses workaround) to the cppcheck dev team...Sikorsky
What happens if you use operator== and do return my_string == "Some text";?Supen
Try to break the statement on more lines and see in wich line the error lies (also the comparison). I have a suspectGelt
@FirstStep "Eventually it does have an impact" - which is?Let
D
6

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

Disputable answered 15/6, 2016 at 9:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.