【发布时间】:2015-12-24 01:42:27
【问题描述】:
我正在接受来自www.adventofcode.com/day/10的挑战
我有一个我认为可行的代码,我使用 c++ 只是为了在玩乐的同时学习。
我正在递归地进行字符串操作。 这里的问题是程序因分段错误而崩溃 进行超过 38 次迭代时,在 "char ch = line[0]" 行上。
#include <iostream>
#include <string>
using namespace std;
string count_chars(string line){
char ch = line[0];
uint i;
for(i = 0; ch == line[i]; i++){
}
if(i != line.length()){
line = to_string(i) + ch + count_chars(line.substr(i));
}
else{
line = to_string(i) + ch;
}
return line;
}
int main(int argc, char** args)
{
//ifstream in("dayx");
/*
if(argc ==1)
return 1;
string line;
cout << line.capacity() << endl;
line = args[1];
*/
string line = "1";
for(int i = 1; i < 40; i++){
line = count_chars(line);
//cout << line << " after " << i << " iterations" << endl;
cout <<"Line size: " << line.size() << endl;
}
cout << line << endl;
}
代码编译使用:
g++ day10.cpp --std=c++11 -g
我的问题,为什么会发生这种情况,我该如何防止它以及如何使用 gdb 来解决这个问题?谢谢!
我使用的是 linux 和 gcc 5.3
【问题讨论】: