Wierd behaviour. Runtime error on B<=8 and no error on B>8

programming
Tags: #<Tag:0x00007f242134ead0>

#1

Can anyone explain this weird behavior why am I getting this?

#include<bits/stdc++.h>

using namespace std;

int mod = 1000000007;

int solve(int A, int B){
    vector<vector<long>> dp(A+1,vector<long>(B+1,0));
    for(int i=0; i<=9; i++){
        dp[1][i] = 1;
    }
    for(int i=0; i<=A; i++){
        dp[i][0] = 0;
    }
    dp[0][0] = 1;
    for(int i=2; i<=A; i++){
        for(int j=1; j<=B; j++){
            dp[i][j] = 0;
            for(int k=0; k<10; k++){
                if(j>=k){
                    dp[i][j] = (dp[i][j]%mod + dp[i-1][j-k]%mod)%mod;
                }
                else{
                    break;
                }
            }
        }
    }
    return dp[A][B];
}

int main(){
    // S>8 no error, S<=8 runtime error(free(): invalid pointer)
    int N = 9;
    int S = 8;
    int res = solve(N,S);
    cout<<res<<endl;
    return 0;
}

#2

While initializing you are going till B=9, but for B<9 that is not possible.


#3

use i<=min(9,B) while defining the base condition initially.