【问题标题】:segmentaion fault on large recursive string manipulation大型递归字符串操作的分段错误
【发布时间】: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

【问题讨论】:

    标签: c++ linux gcc gdb


    【解决方案1】:

    由于递归太深(数千次调用很深)而导致堆栈溢出。您可以使用循环轻松实现该算法。

    【讨论】:

    • 你知道我如何使用调试器来获取这些信息吗,gdb 是一个功能强大但对用户不太友好的程序。
    • @Kristofer type bt 当你的程序崩溃并且你会看到调用堆栈
    【解决方案2】:

    我怀疑任何访问可能不存在的字符串索引的代码行:

       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));
    
    1. 即使字符串为空,它也会从字符串中抓取第一个字符。

    2. 它只检查 i 是否与字符串的长度相同 - 而不是 i 是否大于字符串的长度。

    【讨论】:

    • 感谢您的意见,这似乎是一种很好的做法,值得思考。在这种情况下认为这不是问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多