段错误 - 核心转储
问题描述:
这里是我的代码:段错误 - 核心转储
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string checkpalindrome(string sentence){
sentence.erase(std::remove(sentence.begin(), sentence.end(), ' '), sentence.end());
int unsigned i = 0;
for (i = 0; i < sentence.length(); i++){
sentence[i] = tolower(sentence[i]);
}
if (sentence == string(sentence.rbegin(), sentence.rend())){
cout << sentence << " is a palindrome." << endl;
}
if(sentence != string(sentence.rbegin(), sentence.rend())){
cout << sentence << " isn't a palindrome." << endl;
}
return 0;
}
int main(){
int x = 1;
string originalsentence;
while (x == 1){
int input;
string sentence;
cout << "Press 1 to reverse a string, 2 to check a palindrome, and anything else to quit: ";
cin >> input;
if(input == 1){
cout << "Enter a sentence to reverse: ";
cin.ignore(256, '\n');
getline(cin,originalsentence);
sentence = originalsentence;
cout << string(sentence.rbegin(), sentence.rend()) << endl;
}
if(input == 2) {
cout << "Enter a sentence to check: ";
cin.ignore(256, '\n');
getline(cin,originalsentence);
sentence = originalsentence;
checkpalindrome(sentence);
}
cout << "Hit 1 if you want to continue, anything else to quit: ";
cin >> x;
}
}
程序完成,并做一切它应该做的,当我做选项2,检查是否有回文,在最后,它总是除核心转储。我试过包括cin.ignore的,但他们没有帮助。有任何想法吗?
编辑1:所以我改变了g ++抛出的三个警告。他们分别是palindrome.cpp:19: warning: comparison between signed and unsigned integer expressions palindrome.cpp:29: warning: no return statement in function returning non-void palindrome.cpp:35: warning: unused variable âaâ
我把int i改为无符号,在28返回0,并删除了a。现在,当我编译它没有给出任何错误,但是当我运行它时仍然会在完成回文检查时崩溃,并出现此错误。 terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct NULL not valid Abort (core dumped)
还有什么想法?
答
从问题复制:
固定!我所需要做的只是return sentence
,现在它没有错误地出现
您是否试过编译时打开了警告?我认为大多数编译器会注意到这个问题。 – 2013-02-28 18:11:22
调试以确定分段溢出的确切位置。 – user1929959 2013-02-28 18:13:07
所以我修复了错误,更新了我的上面的代码,并且给了我一个新的错误! – stormcynk 2013-02-28 18:20:21