Menu

false positive: returnDanglingLifetime

CHR
2021-01-07
2021-01-07
  • CHR

    CHR - 2021-01-07
     struct Entry {
      int Int{};
     };
    
     struct Info {
      int* PInt{};
      Entry* PSrc{};
     };
    
     Entry* GetEntry();
    
    Info GetInfo()
    {
      Info info;
      info.PSrc = GetEntry();
      if (info.PSrc)
        info.PInt = &info.PSrc->Int;
    
      return info;
    }
    

    Output from "C:\Program Files\Cppcheck\cppcheck.exe" --inconclusive --enable=all foo.cpp:

    foo.cpp:43:10: error: Returning object that points to local variable 'PSrc' that will be invalid when returning. [returnDanglingLifetime]
      return info;
             ^
    foo.cpp:41:17: note: Address of variable taken here.
        info.PInt = &info.PSrc->Int;
                    ^
    foo.cpp:31:10: note: Variable created here.
      Entry* PSrc{};
             ^
    foo.cpp:43:10: note: Returning object that points to local variable 'PSrc' that will be invalid when returning.
      return info;
    

    Of course, there is no local variable PSrc...

     

    Last edit: CHR 2021-01-07
  • Daniel Marjamäki

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

     
  • CHR

    CHR - 2021-01-07

    Thank you. The warning can be avoided if std::addressof() is used instead of &. Is cppcheck supposed to know std::addressof?

     

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.