Menu

False positive: danglingTemporaryLifetime

CHR
2020-09-16
2020-09-17
  • CHR

    CHR - 2020-09-16

    cppcheck seems to not recognize overloaded operator=(const char*) and similar functions, which do not save their pointer argument.

    #include <iostream>
    #include <cstring>
    #include <string>
    
    struct String {
        char* p{};
        String() = default;
        String(const String&) = delete;
        String(String&&) = delete;
        ~String() { delete p; }
        String& operator=(const String&) = delete;
        String& operator=(const char* s) {
            if (s == nullptr || s == p)
                return *this;
            const size_t length = strlen(s) + 1;
            delete p;
            p = new char[length];
            strncpy(p, s, length);
            return *this;
        }
    };
    
    std::string bar() { return "bar"; }
    
    bool foo() {
        String S;
        S = bar().c_str();
    
        std::cout << S.p << '\n'; // Using object to temporary. [danglingTemporaryLifetime]
        return S.p != nullptr;
    }
    
    int main() {    
        return foo() ? EXIT_SUCCESS : EXIT_FAILURE;
    }
    
     
  • Paul Fultz

    Paul Fultz - 2020-09-17

    Running on the latest from git, I dont see an error.

     
  • CHR

    CHR - 2020-09-17

    That's nice to hear, looking forward to v2.2.

     

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.