Reputation: 1953
I'm new to C++ and the memory nuances that are needed to write and debug the language. Can anyone tell me why the following code is giving me a segmentation fault?
string Polynomial::toString(){
int i, exponent;
stringstream result;
for (i = 0; i < coeffs.size(); i++){
// For first non-zero coefficient
if (result.str().empty()){
if(coeffs[i] < 0)
result << "-";
if(coeffs[i] != 0)
result << coeffs[i];
}
else{
if(coeffs[i] < 0)
result << " - " << abs(coeffs[i]);
else if(coeffs[i] > 0)
result << " + " << coeffs[i];
}
exponent = (coeffs.size() - i - 1);
if (coeffs[i] != 0){
if (exponent > 1)
result << coeffs[i] << "x^" << exponent;
else if(exponent == 1)
result << coeffs[i] << "x";
}
}
result.str();
}
Upvotes: 0
Views: 232
Reputation: 61970
Your function is missing a return statement (probably just the return
part). According to the standard, reaching the closing brace on any function besides main
that has a return type is undefined behaviour, as per §6.6.2/2 of the C++11 standard, shown below, which usually results in a crash, though it might not always do so.
Other than that, there's nothing that could cause undefined behaviour or a crash. What you want to do is add the return
part:
return result.str();
For what it's worth, GCC 4.7.2 gives the following warning:
warning: no return statement in function returning non-void [-Wreturn-type]
Always take advantage of the warnings compilers can and will give you.
Standard reference:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
Upvotes: 1
Reputation: 227548
You are probably calling the function and assigning the result to something:
Polynomial p = ....;
std::string s = p.toString();
Since you have no return statement in Polynomial::toString()
, which in itself is undefined behaviour, this can easily result in a segmentation violation. You can easily fix this by returning the stringstreams
's `string:
return result.str();
Upvotes: 3