-6

I have here some very simple lines of code but they are giving me some serious error messages.

1.My code:

    #include <bits/stdc++.h>

    using namespace std;

    void solve( int n, unsigned long long k, int x){
        unsigned long long divi = 1000000007;
        std::vector< std::vector < unsigned long long > > dpArray( n, std::vector < unsigned long long >( 3, 0));
        dpArray[0][0] = 1;
        for(int index = 1; index < n; index++){
            dpArray[0][index] = (dpArray[1][index - 1] + dpArray[2][index - 1])%divi;
            dpArray[1][index] = (dpArray[0][index - 1] + dpArray[2][index - 1])%divi;
            dpArray[2][index] = ((k - 2)*dpArray[1][index])%divi;
        }

        int ans = 0;
        if(x == 1){
            ans = (int)dpArray[0][n - 1];
        }
        else{
            ans = (int)dpArray[1][n - 1];
        }
        std::cout << ans << std::endl;
    }

    int main(){
        int n = 0, x = 0;
        unsigned long long k;
        std::cin >> n >> k >> x;
        solve( n, k, x);
        return 0;
    }
  1. Below is the error message when I gave the input 100000 10000 1

    151337967
    Error in `./a.out': free(): invalid next size (fast): 0x0000000000818050
    ======= Backtrace: =========
    /lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f90f9af97e5]
    /lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7f90f9b0237a]
    /lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f90f9b0653c]
    ./a.out[0x401aee]
    ./a.out[0x401961]
    ./a.out[0x401730]
    ./a.out[0x401422]
    ./a.out[0x401210]
    ./a.out[0x401c77]
    ./a.out[0x401ab4]
    ./a.out[0x40190d]
    ./a.out[0x4016b1]
    ./a.out[0x40130c]
    ./a.out[0x400f86]
    ./a.out[0x401078]
    /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f90f9aa2830]
    ./a.out[0x400bb9]
    

The first line in stdout is the right answer but then it's giving this error!

1 Answers1

2
std::vector< std::vector < unsigned long long > > dpArray( n, std::vector < unsigned long long >( 3, 0))

this creates vector with size [n][3]. so you are accessing out of index in the following code

for(int index = 1; index < n; index++){
        dpArray[0][index] = (dpArray[1][index - 1] + dpArray[2][index - 1])%divi;
        dpArray[1][index] = (dpArray[0][index - 1] + dpArray[2][index - 1])%divi;
        dpArray[2][index] = ((k - 2)*dpArray[1][index])%divi;
    }
LearningC
  • 3,182
  • 1
  • 12
  • 19