How to fix this SEGFAULT

Pages: 12
Guys the following code works fine. So does everything else.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <vector>

int main()
{
    typedef std::vector<unsigned int> int_v;
    int_v p(0);
    unsigned int s = 3456;
    std::string b = std::to_string(s*s);
    for (unsigned int i = 0; i < b.size(); i++){
        if (b[i] == '0'){
            b.erase(i, 1);
        }
    }
    if (b.size() == 8){
        b.erase(0, 2);
        b.erase(b.begin()+4, b.end());
        p.push_back(std::stoi(b, nullptr, 10));
    }
    for(unsigned int i = 0; i< p.size(); i++){
        std::cout<<p[i] << " ";
    }
}


The problem is this line: fpR(std::stoi(b, nullptr, 10), p--, r);

Guys, there's no need to look for a solution for this problem, I did that on my own. But the question will remain open since I'm not quite sure why std::stoi falls apart whenever I use it as an argument of a recursive function.

Thanks a lot everyone for helping me out and for giving me those suggestions! :)

Here's what I did:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
void fpR(unsigned int s, unsigned int pe, int_v& p){
    std::string b;
    while (pe > 0){
        b = std::to_string(s*s);
        b.erase( std::remove_if( b.begin(), b.end(), [](char c){return c == '0';} ), b.end() ); 
        if (b.size() == 8){
            b.erase(0, 2);
            b.erase(b.begin()+4, b.end());
            p.push_back(std::stoi(b, nullptr, 10));
        }
        else if (b.size() == 7){
            b.erase(0, 2);
            b.erase(b.begin()+4, b.end());
            p.push_back(std::stoi(b, nullptr, 10));
        }
        else if (b.size() == 6){
            b.erase(0, 2);
            p.push_back(std::stoi(b, nullptr, 10));
        }
        else if (b.size() == 5){
            b.erase(0, 1);
            p.push_back(std::stoi(b, nullptr, 10));       
        }
        else if (b.size() == 4){
            p.push_back(std::stoi(b, nullptr, 10));
        }
        else {
            s+=101;
            continue;
        }
        s = std::stoi(b, nullptr, 10);
        pe--;
        
    }
}


@Thomas1965 I used the erase-remove idiom and a lambda instead. I don't think that the code you provided works and I suppose the method I used is quicker, unfortunately I can't test that right now, because I can't use my IDE.

Again, thanks everyone for your help!
Last edited on
Topic archived. No new replies allowed.
Pages: 12