Visitar URL original
#10975 (false negative: dangling reference in class) – Cppcheck

Opened 5 years ago

Closed 5 years ago

#10975 closed enhancement (fixed)

false negative: dangling reference in class

Reported by: kidkat Owned by: pfultz2
Priority: Normal Milestone: 2.8
Component: Improve check Version:
Keywords: lifetime Cc:

Description

Based on an issue I might have introduced in ​https://github.com/danmar/simplecpp/pull/254-

#include <string>
#include <vector>

class A {
public:
    A(std::vector<std::string> &filenames);
private:
    std::vector<std::string> &files;
};

A::A(std::vector<std::string> &filenames)
: files(filenames) {}

A make()
{
    std::vector<std::string> files;
    return A(files);
}
##file input.cpp
4: class A {
5: public:
6: A ( std :: vector < std :: string > & filenames@var1 ) ;
7: private:
8: std :: vector < std :: string > & files@var2 ;
9: } ;
10:
11: A :: A ( std :: vector < std :: string > & filenames@var3 )
12: : files@var2 ( filenames@var3 ) { }
13:
14: A make ( )
15: {
16: std ::@expr5 vector < std ::@expr6 string > files@var4 ;
17: return A (@expr7 files@var4 ) ;
18: }



##Value flow
Line 17
  files always size=0

The actual code did not see the implementation of the constructor so that case seems impossible to be detected. If we do see the code we might be able detect this.

Change History (5)

comment:1 by pfultz2, 5 years ago

Keywords: lifetime added

comment:2 by pfultz2, 5 years ago

Milestone: → 2.8
Owner: changed from noone to pfultz2
Status: new → accepted

comment:4 by kidkat, 5 years ago

This also fixes the inconclusive version I ran into in the same PR:

#include <string>

struct A {
    A(std::string &s);
};

static A f()
{
    std::string s;
    return A(s);
}
input.cpp:10:13: error: inconclusive: Returning object that points to local variable 's' that will be invalid when returning. [returnDanglingLifetime]
    return A(s);
            ^
input.cpp:10:14: note: Passed to constructor of 'A'.
    return A(s);
             ^
input.cpp:9:17: note: Variable created here.
    std::string s;
                ^
input.cpp:10:13: note: Returning object that points to local variable 's' that will be invalid when returning.
    return A(s);
            ^

comment:5 by kidkat, 5 years ago

Resolution: → fixed
Status: accepted → closed
Note: See TracTickets for help on using tickets.