Menu

[2.4.1] False positive: danglingTempReference

2021-04-08
2021-04-10
  • scott snyder

    scott snyder - 2021-04-08

    hi -

    This example gives a false positive with cppcheck 2.4.1:

    struct Elt
    {
      void foo();
    };
    template <class T>
    struct Subset
    {
      typedef Elt& Reference;
    };
    struct Cont
    {
      Subset<Elt>::Reference get();
    };
    
    
    void f (Cont* c)
    {
      Elt& e = c->get();
      e.foo();
    }
    
    $ cppcheck x.cc
    Checking x.cc ...
    x.cc:19:3: error: Using reference to dangling temporary. [danglingTempReference]
      e.foo();
      ^
    x.cc:18:10: note: Assigned to reference.
      Elt& e = c->get();
             ^
    x.cc:19:3: note: Using reference to dangling temporary.
      e.foo();
      ^
    

    I can fix this with this change. I don't observe any changes to the
    make test results.

    diff --git a/lib/symboldatabase.cpp b/lib/symboldatabase.cpp
    index 41498ae58..2a827b929 100644
    --- a/lib/symboldatabase.cpp
    +++ b/lib/symboldatabase.cpp
    @@ -2642,7 +2642,10 @@ bool Function::returnsReference(const Function* function,
     bool unknown)
         const Token* start = function->retDef;
         while (Token::Match(start, "const|volatile"))
             start = start->next();
    -    if (start->tokAt(1) == defEnd && !start->type() && !start->isStandardType()
    )
    +    int iat = 1;
    +    while (start->tokAt(iat) && start->tokAt(iat)->str() == "::")
    +      iat += 2;
    +    if (start->tokAt(iat) == defEnd && !start->type() && !start->isStandardType())
             return unknown;
         // TODO: Try to deduce the type of the expression
         if (Token::Match(start, "decltype|typeof"))
    
     
  • Daniel Marjamäki

    Thanks! I can reproduce.

    Somehow the typedef should be handled better. From the --debug output:

    12: Subset<Elt> :: Reference get ( ) ;
    

    Since the typedefs are simplified it would have been better if that line said Elt& get ( ) ; instead. I have created https://trac.cppcheck.net/ticket/10239 for that.

    I will look at the returnsReference also..

     
  • Daniel Marjamäki

    I made a fix also inspired by your code eacc9e552ebcb0550cbec8f930e5ab72f58285c9

     

Log in to post a comment.