diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp index a5dd03810..de001bb45 100644 --- a/lib/checkstl.cpp +++ b/lib/checkstl.cpp @@ -1100,17 +1100,17 @@ void CheckStl::string_c_str() } bool local = false; - bool ptr = false; + bool ptrOrRef = false; const Variable* lastVar = nullptr; const Function* lastFunc = nullptr; bool funcStr = false; if (Token::Match(tok2, "%var% .")) { local = isLocal(tok2); - ptr = tok2->variable() && tok2->variable()->isPointer(); + ptrOrRef = tok2->variable() && (tok2->variable()->isPointer() || tok2->variable()->isReference()); } while (tok2) { if (Token::Match(tok2, "%var% .|::")) { - if (ptr) + if (ptrOrRef) local = false; lastVar = tok2->variable(); tok2 = tok2->tokAt(2); diff --git a/test/teststl.cpp b/test/teststl.cpp index efd98b3c0..20fb6cf4f 100644 --- a/test/teststl.cpp +++ b/test/teststl.cpp @@ -2365,6 +2365,16 @@ private: " return mapInfo.author.c_str();\n" "}"); ASSERT_EQUALS("[test.cpp:6]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n", errout.str()); + + check("struct S {\n" // #7656 + " std::string data;\n" + "};\n" + "const S& getS();\n" + "const char* test() {\n" + " const struct S &s = getS();\n" + " return s.data.c_str();\n" + "}"); + ASSERT_EQUALS("", errout.str()); } void autoPointer() {