From dd7340e5f75f60deeb1ce37b35440a111664fb68 Mon Sep 17 00:00:00 2001 From: Alex Smith Date: Mon, 2 Jan 2023 17:38:26 +0000 Subject: [PATCH] Avoid dereferencing nullptr C-style strings Added runtime checks for C-style strings (char*) being nullptr during matching and serialization. This fix prevents nullptr dereferences in the case that the null character pointer (as opposed to the null nullptr_t) is expected and in the case that a non-null string is expected but nullptr is actually passed. --- include/turtle/matcher.hpp | 7 ++++++- include/turtle/stream.hpp | 8 +++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/include/turtle/matcher.hpp b/include/turtle/matcher.hpp index 7854d77..fc20a22 100644 --- a/include/turtle/matcher.hpp +++ b/include/turtle/matcher.hpp @@ -39,7 +39,12 @@ class matcher { public: explicit matcher(const char* expected) : expected_(expected) {} - bool operator()(const char* actual) { return std::strcmp(actual, expected_) == 0; } + bool operator()(const char* actual) + { + if (nullptr == actual || nullptr == expected_) + return actual == expected_; + return std::strcmp(actual, expected_) == 0; + } friend std::ostream& operator<<(std::ostream& s, const matcher& m) { return s << mock::format(m.expected_); } private: diff --git a/include/turtle/stream.hpp b/include/turtle/stream.hpp index 52991ed..e3bf273 100644 --- a/include/turtle/stream.hpp +++ b/include/turtle/stream.hpp @@ -106,7 +106,13 @@ namespace detail { { s << '"' << str << '"'; } - inline void serialize(stream& s, const char* const str) { s << '"' << str << '"'; } + inline void serialize(stream& s, const char* const str) + { + if (nullptr != str) + s << '"' << str << '"'; + else + s << "nullptr"; + } inline void serialize(stream& s, unsigned char c) { s << static_cast(c); } } // namespace detail } // namespace mock