Misgevolution
Misgevolution

Reputation: 845

How to check type safety in cppcheck or clang?

I want the static analyzer to warn me about the invalide rvalue dereference in the following code.How can I do it in clang or cppcheck?

#include <memory>

using namespace std;

unique_ptr<int> myfunc(void)
{
    unique_ptr<int> a(new int(2));
    return a;
}


int main()
{
    const int& ra = *myfunc();
    return 0;   
}

Upvotes: 2

Views: 580

Answers (1)

Daniel Marjam&#228;ki
Daniel Marjam&#228;ki

Reputation: 3037

I am a Cppcheck developer.

Cppcheck has a related checker for std::string. For instance, you get a Cppcheck warning for this code:

std::string hello();

unsigned int f() {
    const char *p = hello().c_str();
    return 0;
}

The warning you get is:

[2.cpp:4]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.

It is reported because the returned std::string object is deleted immediately. Dereferencing the pointer p anywhere after the initialization is UB.

I think it would be great to have a warning for your unique_ptr code also.

If you are interested.. feel free to help us with this.

Upvotes: 4

Related Questions