Menu

Possible FP in [invalidLifetime] with string_view

ashimaru
2023-01-19
2023-01-27
  • ashimaru

    ashimaru - 2023-01-19

    When uplifting to cppcheck 2.9 I got report on this code:

    #include <string_view>
    #include <string>
    #include <charconv>
    
    std::string getValue()
    {
        return "123";
    }
    
    template<class T>
    T textToNumber(std::string_view text)
    {
        T result{};
        std::from_chars(text.data(), text.data() + text.size(), result); //Using object that points to local variable 'str' that is out of scope. [invalidLifetime]
        return result;
    }
    
    int f()
    {
        const auto str = getValue(); //Variable created here.
        return textToNumber<int>(str);
    }
    

    For me it looks like FP since str is not out of range.
    You can find full file in the attachment

    Have a great day!

     
  • CHR

    CHR - 2023-01-20

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

     
  • ashimaru

    ashimaru - 2023-01-27

    Hi again!
    I am trying to investigate this issue and managed to simplify this issue further:

    int textToNumber(std::string_view text);
    void f() {
        std::string teststr;
        textToNumber(teststr);
    }
    
    void textToNumber(std::string_view text) {
        g(text.data());
    }
    

    I also did some digging around and it seems that in condition in checkautovariables.cpp:588 (as for f16ffd88e96efc4ab5a538fa61197741be6fee3b) marks error because 'textToNumber' function's scope ends after 'f''s end of scope.

    This issue is not visible if std::string_view is replaced with const std::string&. I am not sure how to apporach it, should std::string_view be translated into a reference or a pointer to original string?

     

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.