c++recursionsegmentation-faultbus-error

Bus Error when using recursion


So, I'm using recursion and going through an array named code which contains integers and a value is computed after traversing through the array. But I don't know for what reason this is giving a BUS ERROR : 10. I even tried manually going through the array and everything seems fine, array is sufficiently big.

//change to bits/stdc++.h
#include "stdc++.h"
#define MAX 5001
typedef unsigned long long ull;
typedef  long long ll;

using namespace std;
int code[MAX];
int co_code;

ull rec(int i, int j, int k){
   if(k==j-1)
     return 0;
   if(i==j-1)
     return (rec(k+2, j, k+2));
   int temp = code[i]*10 + code[i+1];
   if(temp<=26)
      return (1 + rec(i+1, j, k));
   else
     return (rec(i+1, j, k));
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    while(1){
        memset(code, 0, sizeof(code[0])*MAX);
        string str;
        cin>>str;
        size_t size = str.length();
        co_code = 0;
        while(co_code!= size){
            code[co_code] = str[co_code] - '0';
            co_code++;
           }
        if(code[0] == 0)
            break;
        cout<<rec(0, co_code-1, 0) + 1;
       }
return 0;
}

Solution

  • The error is in accessing the array outside the size given by co_code, so it can be fixed by changing the if condition.

    Corrected : -

    if(k>=j-1)