0

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
sesodesa
  • 1,473
  • 2
  • 15
  • 24
  • 3
    You are dereferencing a `nullptr` with `*printStream << ...`. That is undefined behavior. Note that you are not _feeding_ a `nullptr` _to_ `std::ostream` but trying to _use_ `nullptr` _as_ a `std::ostream`. What is the behavior you expect? – Max Langhof Oct 02 '19 at 14:27
  • 1
    @Max Langhof Ah, true that. Maybe the sensible thing to do is to not perform that particular test at all? – sesodesa Oct 02 '19 at 14:31
  • 2
    Another sensible thing would be to take the `printStream` by reference. I don't think the function can do anything meaningful when given a `nullptr`, so why allow it semantically? – Max Langhof Oct 02 '19 at 14:33
  • 1
    So define `Date::print` as `void Date::print(std::ostream &printStream) const;` instead of `void Date::print(std::ostream *printStream) const;`? – sesodesa Oct 02 '19 at 14:46
  • 1
    Yes, that looks good. – Max Langhof Oct 02 '19 at 14:46
  • I don't get the question. What else do you think dereferencing a null pointer means? – L. F. Oct 03 '19 at 06:44

0 Answers0