Skip to content

Invalid use of pointer in notnull_tests.cpp TEST_CASE("TestNotNullostream") #737

@stayprivates

Description

@stayprivates

Detected with the help of valgrind which shows strlen accessing invalid memory. In the excerpt below, p is a pointer to a single char, but the ostream::operator()<< does not know this and assume it's a pointer to char, and will end up calling strlen via _Traits::length(__s)). Turns out there is a null terminator in memory, 29 bytes after the 'c', so no crash and the test passes. I solved this by casting to void * p and &v.

TEST_CASE("TestNotNullostream")
{
...
    ostream_helper<char>('c');
...
 }

void ostream_helper(T v)
{
    not_null<T*> p(&v);
    {
        std::ostringstream os;
        std::ostringstream ref;
        os << p;   ///// HEREHERE
        ref << &v; ///// HEREHERE
        CHECK(os.str() == ref.str());
    }
}

For reference here is the code to operator<<


template<class _Traits>
    inline basic_ostream<char, _Traits>&
    operator<<(basic_ostream<char, _Traits>& __out, const char* __s)
    {
      if (!__s)
	__out.setstate(ios_base::badbit);
      else
	__ostream_insert(__out, __s,
			 static_cast<streamsize>(_Traits::length(__s))); ///// HEREHERE
      return __out;
    }


Metadata

Metadata

Assignees

No one assigned

    Labels

    Help WantedNeeds additional help or expertise

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions