Darth Vader Darth Vader - 2 months ago 8
C++ Question

Why do I get a SIGSEGV when I use my overloaded insertopm (<<) operator?

I'm taking a C++ class, and for my most recent assignment, I have to create a

Box
class. Overall, the assignment has actually been a walk in the park, but I'm having some trouble with the overloaded insertion operator I am supposed to create. The insertion operator is declared in
box.h
, and defined in
box.cpp
, as is standard. In the
Box
class, I have a
print(std::ostream &) const
function. All the overloaded insertion operator does is call the
print
function on the
std::ostream &
provided to the operator. Relevant code:

void Box::print(std::ostream &outStream) const { // The java in me loves abstraction
if ((_boxType == BoxType::FILLED) || (_boxType == BoxType::HOLLOW))
_printFilledOrHollow(outStream);
else if (_boxType == BoxType::CHECKERED)
_printCheckered(outStream);
}

void Box::_printFilledOrHollow(std::ostream &outStream) const {
if (_width > 1) {
outStream << string(_width, 'x') << endl;
for (int i = 0; i < (_height - 2); i++) { //works for everything but 1
if (_boxType == Box::FILLED)
outStream << string(_width, 'x') << endl;
else
outStream << "x" << string((_width - 2), ' ') << "x" << endl;
}
outStream << string(_width, 'x') << endl;
} else
outStream << "x" << endl; //which is what this is for
}

void Box::_printCheckered(std::ostream &outStream) const {
if (_boxType == Box::CHECKERED) {
for (int row = 0; row < _height; row++) {
for (int col = 0; col < _width; col++) {
if ((row % 2) == 0) { // if even column
if (col % 2 == 0)
outStream << "x";
else
outStream << " ";
} else {
if ((col % 2) != 0)
outStream << "x";
else
outStream << " ";
}
}

cout << endl;
}
}
}

std::ostream &operator<<(std::ostream &outStream, const Box &rhs) {
rhs.print(outStream);
}


Now, here's the really weird part. If I add something to the tune of
cout << "";
to the end of the
Box::print
function, it completes as intended, without the SIGSEGV. I'm completely and totally stumped by this, and was hoping you guys could at least clue me in to why this is happening. If necessary, I'll turn it it with
cout << ""
at the end of
Box::Print
, but I would really prefer to get a handle on this error. Thanks!

Answer

You forgot the return statement in your operator. In Java, it wouldn't even compile, but C++ is more “permissive” meaning that you get UB instead.

As @Eichhörnchen mentioned in the comment, enabling compiler warnings is a must-do when dealing with C++.