Menu

False positive: null pointer dereference in template function call

2023-02-10
2023-02-10
  • Oleg Pykhov

    Oleg Pykhov - 2023-02-10

    I'd like to report a bug. Not sure if it's duplicated, I have not found anything like that on tracker.
    Consider this piece of C++ code:

    #include <string>
    
    template <typename T>
    void foo(T& val) {}
    
    template <>
    void foo<std::string>(std::string& val) {}
    
    int main() {
        int val = 0;
        foo(val);
        return 0;
    }
    

    Cppcheck 2.9 would produce following results after its' analysis:

    $ cppcheck main.cpp
    Checking main.cpp ...
    main.cpp:11:9: error: Null pointer dereference [nullPointer]
        foo(val);
            ^
    

    It does not raise an error if:

    • template specialization is made for any type (among those I tried) other than std::string;
    • foo(val) -> foo<int>(val);
    • val = 0 -> val = 1, val = -1, etc.

    According to C++ template argument deduction rules, foo(val) line should produce call to instantiation of template function with T = int. And it does indeed (see source and g++ disassembly in attachments).

    Following speculations is how I see the problem. I suspect that for some reason cppcheck fails to handle type deduction and assuming that in this line calling foo<std::string>(std::string&) has been made. Therefore val value is considered to be pointer to const char* which passed to the std::string constructor and dereferenced in it.

     

    Last edit: Oleg Pykhov 2023-02-10
  • CHR

    CHR - 2023-02-10

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/11551

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.