运行C++单词统计代码返回-11(SIGSEGV)错误该如何排查
问题排查说明
SIGSEGV(对应返回码-11)是程序访问非法内存触发的段错误,你的代码中直接引发崩溃的是循环变量操作错误,同时还存在多处逻辑问题:
- 【崩溃直接原因】内层循环变量操作错误
你编写的统计次数嵌套循环存在笔误:
for(int i = 0; i < words.size(); i++){ for(int j = 0; j < words.size(); i++){ // 此处错误,应该是j++而非i++ if(words[i] == words[j]){ count++; } } numTimes.push_back(count); }
内层循环每次执行都在给i自增,会导致i快速超出words数组的合法下标范围,访问words[i]时触发非法内存访问,直接引发段错误。
- 【计数逻辑错误】count变量未初始化、未归零
你声明int count;后没有赋初始值,且每次外层循环统计新单词的出现次数前,没有将count重置为0,会导致计数结果完全错误。 - 【单词拆分逻辑错误】丢失最后一个单词
separate函数只有碰到空格时才会将当前拼接的单词存入容器,如果输入字符串的末尾没有空格,最后一个单词会被直接丢弃,不会存入返回的vector。 - 【边界异常】连续空格会存入空字符串
如果输入中存在多个连续空格,代码会在每次碰到空格时都存入当前空的build变量,导致vector里出现多余的空字符串元素。
修复后完整代码
#include <iostream> #include <vector> #include <string> using namespace std; vector<string> separate(string str){ string build = ""; vector<string> temp; for(int i = 0;i < str.size(); i++){ if(str[i] != ' '){ build += str[i]; } else { // 只有当前build不为空的时候才存入,避免连续空格生成空单词 if(!build.empty()){ temp.push_back(build); build = ""; } } } // 循环结束后补充存入最后一个单词 if(!build.empty()){ temp.push_back(build); } return temp; } int main() { string sentence; vector<int> numTimes; getline(cin, sentence); vector<string> words = separate(sentence); for(int i = 0; i < words.size(); i++){ int count = 0; // 每次统计新单词前初始化count为0 for(int j = 0; j < words.size(); j++){ // 修复循环变量为j++ if(words[i] == words[j]){ count++; } } numTimes.push_back(count); } for(int k = 0; k < words.size(); k++){ cout << words[k] << " - " << numTimes[k] << endl; } return 0; }
内容的提问来源于stack exchange,提问作者Charles Simmons
相关产品推荐
相关产品推荐

