Menu

Operator overloading, implicit conversion, and false-positive "Returning pointer to local variable"

2023-07-11
2023-07-12
  • Andrey Alekseenko

    Hi! The following code triggers a false-positive warning with a recent main (80c42fcaf305014ba7eaf4e234ee029a87819d44):

    typedef float rvec[2];
    
    class RVec {
    public:
      RVec(float x, float y) : x_{x, y} {}
      RVec(const rvec x) : x_{x[0], x[1]} {}
      float operator[](int i) const { return x_[i]; }
      RVec operator+(const RVec &right) const {
        return {x_[0] + right[0], x_[1] + right[1]};
      }
      rvec x_;
    };
    
    int main() {
      auto foo = [](RVec x) {
        rvec dx;
        dx[0] = dx[1] = 1.F;
        return x + dx;
      };
    }
    
    Checking test_add.cpp ...
    test_add.cpp:18:14: error: Returning pointer to local variable 'dx' that will be invalid when returning. [returnDanglingLifetime]
        return x + dx;
                 ^
    test_add.cpp:18:16: note: Array decayed to pointer here.
        return x + dx;
                   ^
    test_add.cpp:16:10: note: Variable created here.
        rvec dx;
             ^
    test_add.cpp:18:14: note: Returning pointer to local variable 'dx' that will be invalid when returning.
        return x + dx;
                 ^
    

    We are not doing any pointer arithmetics here, since dx is converted to RVec, and then the overloaded operator+ is used.

     
  • CHR

    CHR - 2023-07-11

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

     
  • Andrey Alekseenko

    Thanks!

     

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.