From f83eb127aea5bc6ae7c62fbfc796cbb1c9d38211 Mon Sep 17 00:00:00 2001 From: Rikard Falkeborn Date: Sun, 20 Oct 2019 21:02:28 +0200 Subject: [PATCH] ValueFlow: sizeof string and char literals (#2285) --- lib/valueflow.cpp | 14 ++++++++++++++ test/testvalueflow.cpp | 13 +++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index 0897c587f..985b7a06d 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -1232,6 +1232,20 @@ static Token * valueFlowSetConstantValue(Token *tok, const Settings *settings, b setTokenValue(tok->next(), value, settings); } } + } else if (tok2->tokType() == Token::eString) { + size_t sz = Token::getStrSize(tok2, settings); + if (sz > 0) { + ValueFlow::Value value(sz); + value.setKnown(); + setTokenValue(const_cast(tok->next()), value, settings); + } + } else if (tok2->tokType() == Token::eChar) { + size_t sz = ValueFlow::getSizeOf(*tok2->valueType(), settings); + if (sz > 0) { + ValueFlow::Value value(sz); + value.setKnown(); + setTokenValue(tok->next(), value, settings); + } } else if (!tok2->type()) { const ValueType &vt = ValueType::parseDecl(tok2,settings); const size_t sz = ValueFlow::getSizeOf(vt, settings); diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index 5716741d2..ca8b00bce 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -813,6 +813,19 @@ private: CHECK("int", settings.sizeof_int); CHECK("long", settings.sizeof_long); CHECK("wchar_t", settings.sizeof_wchar_t); + + // string/char literals + CHECK("\"asdf\"", 5); + CHECK("L\"asdf\"", 5 * settings.sizeof_wchar_t); + CHECK("u8\"asdf\"", 5); // char8_t + CHECK("u\"asdf\"", 5 * 2); // char16_t + CHECK("U\"asdf\"", 5 * 4); // char32_t + CHECK("'a'", 1U); + CHECK("'ab'", settings.sizeof_int); + CHECK("L'a'", settings.sizeof_wchar_t); + CHECK("u8'a'", 1U); // char8_t + CHECK("u'a'", 2U); // char16_t + CHECK("U'a'", 4U); // char32_t #undef CHECK // array size