Menu

Possible spurious returnDanglingLifetime error

T Tanner
2022-07-02
2022-07-05
  • T Tanner

    T Tanner - 2022-07-02

    This code:

    #include <set>
    
    struct Somestruct { int a; int b; Somestruct(int a, int b) : a(a), b(b) {} }
    
    typedef set<Somestruct> SomeSet;
    
    static SomeSet stuff;
    
    Somestruct *addit()
    {
        std::pair<SomeSet::iterator,bool> result(stuff.insert(Somestruct(1, 2)));
        Somestruct * impl = const_cast<Somestruct*>(&*result.first);
        return impl;
    }
    

    generates this output

    $ cppcheck test.cc
    Checking test.cc ...
    test.cc:13:12: error: Returning pointer that will be invalid when returning. [returnDanglingLifetime]
        return impl;
               ^
    test.cc:12:49: note: Address of variable taken here.
        Somestruct * impl = const_cast<Somestruct*>(&*result.first);
                                                    ^
    test.cc:13:12: note: Returning pointer that will be invalid when returning.
        return impl;
               ^
    

    as far as I can tell that is entirely valid because it is just de-referencing the iterator which points to something inside the set.

    (cppcheck 2.8)

     

    Last edit: T Tanner 2022-07-02
  • Daniel Marjamäki

    Thanks! I have created https://trac.cppcheck.net/ticket/11168

    looks a bit tricky to fix. but of course it should be fixed.

     
  • T Tanner

    T Tanner - 2022-07-05

    thanks. appreciated

     

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.