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:
I checked if the string my_string is empty.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With