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.
This commit is contained in:
Alex Smith 2023-01-02 17:38:26 +00:00
parent 528761b180
commit dd7340e5f7
2 changed files with 13 additions and 2 deletions

View file

@ -39,7 +39,12 @@ class matcher<const char*, const char*>
{
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:

View file

@ -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<int>(c); }
} // namespace detail
} // namespace mock