mercredi 2 octobre 2019

Why does feeding a nullptr to std::ostream produce a signal 11, aka segmentation fault, from the OS, and how do I handle it?

I have a Date class with a Date::print method, that I'm attempting to test. The method itself is defined as

void Date::print(std::ostream *printStream) const
{
  invariant();
   printStream << day_ << '.' << month_ << '.' << year_;
}

and the test function as

void Unittest::print()
{
    // Creating and printing the date into string, checking if ok
    Date d(4, 5, 2000);
    std::ostringstream printStream;
    d.print(&printStream);
    QCOMPARE(printStream.str(), std::string("4.5.2000"));

    // Testing with a nullptr
    d.print(nullptr);
}

The valid date passes the test, no problem, but testing for a nullptr produces a segmentation fault. How should I modify the method definition to handle the nullptr case?

Aucun commentaire:

Enregistrer un commentaire