Question

Here is the code snippet or rather a function which takes two strings as inputs which are basically large integers and prints the sum of them. I am getting the sum printed correctly, but a segmentation fault comes up at the end and I am unable to figure out its source.

string sum(string x, string y) {
    bool carry = false;
    int yLen = y.length(), xLen = x.length();
    vector<char> s;
    for(int i = xLen - 1, j = yLen - 1; i >= 0, j >= 0; i--, j--) {
        int a = x[i] - '0', b = y[j] - '0';
        int c = (carry?(a+b+1):(a+b));
        if(c/10)        carry = true, c %= 10;
        else            carry = false;
        s.push_back(c + '0');
    }
    for(int i = xLen - yLen - 1; i >= 0; i--) {
        int a = x[i] - '0';
        int c = (carry?(a+1):(a));
        if(c/10)        carry = true, c %= 10;
        else            carry = false;
        s.push_back(c + '0');
    }
    reverse(s.begin(), s.end());
    for(vector<char>::iterator i = s.begin(); i != s.end(); i++)        cout<<*i;
    cout<<endl;
}

Update: Assume that x.length() is always greater than or equal to y.length() in the input itself.

Was it helpful?

Solution

Your function returns string.

You need to return a string, or change that to void.

void sum(string x, string y) {

Not returning in a value-returning function is undefined behaviour and is probably the cause of your segmentation fault.

OTHER TIPS

This loop statement

for(int i = xLen - 1, j = yLen - 1; i >= 0, j >= 0; i--, j--) {

is already wrong.

The second expression in the loop

i >= 0, j >= 0

is an expression of the comma operator. It does not take into account that i can be less than 0. The value of the expression is the value of the condition j >= 0. So if xLen is less than yLen then you will get that i will be equal to some negative number.

You should rewrite this loop. I think you meant expresssion

i >= 0 && j >= 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top