Reputation: 81
I am writing a fairly simple exercise (homework), and most of it works, however it sometimes segfaults on cin. Here is the relevant code.
int main()
{
std::string str = "";
std::cout << "Please select the desired operation:\n";
std::cout << "(A): Generate Decompositions\n";
std::cout << "(B): Generate Acceptable Compositions from S1.txt and S2.txt\n";
std::cout << "cout"; //debug statement
std::cin >> str;
std::cout << "cin"; //debug statement
std::cout << str;
char resp = str.at(0);
std::cout << "resp"; //debug statement
...
}
I get a segfault on std::cin >> str
(I know this because of what "debug statements" are output). But the weird thing is, I only get it when I input 'b'. If I input 'a', or any word starting with 'a', it works fine. If I enter any letter other than a or b, or anything starting with any other letter than a or b, it exits (as it's supposed to). But if I type in 'b', or any word starting with 'b', it Segfaults. Every single time. Why?
Upvotes: 2
Views: 10205
Reputation: 726569
I know this because of what "debug statements" are output"
The code that you posted looks fine.
Since your output statements do not have << endl
at the end, some of the output may still be buffered at the time of segfault. Writing out endl
blocks until the output is flushed, so adding << endl
is likely to help you get closer to the actual location of the crash.
Upvotes: 8