Why exception is thrown at the end of this code?

1
int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, k;
        cin >> n >> k;
        int* ar1 = new int[n];
        int* ar2 = new int[n];
        /*int ar1[n];
        int ar2[n];*/
        for (int i = 0; i < n; i++) {
            cin >> ar1[i];
        }
        for (int i = 0; i < n; i++) {
            cin >> ar2[i];
        }
        sort(ar1, ar1 + n);
        sort(ar2, ar2 + n, greater<int>());
        int sum = 0;
        for (int i = 0; i < n, k>0; i++) {
            if (ar1[i] < ar2[i]) {
                ar1[i] = ar2[i];
                k--;
            }
        }
        for (int i = 0; i < n; i++) {
            sum += ar1[i];
        }
        cout << sum << "\n";
    }
    return 0;
}

Unhandled exception at 0x77B6EC75 (ntdll.dll) in code.exe: 0xC000000D: An invalid parameter was passed to a service or function. Whenever this code is compiled for the first time, it works fine, but second time it throws an exception. I have submitted this code on codeforces and there it prints 9720301 after printing all the results correctly.

c++
exception
asked on Stack Overflow May 14, 2020 by Lucky One

1 Answer

4

The condition in this loop is wrong:

for (int i = 0; i < n, k>0; i++)

since it might fail even when i>=n (the condition will evaluate i<n, ignore it, and only check if k>0).

Instead, you need to do:

for (int i = 0; i < n && k > 0; i++) 

to check that both the conditions are satisfied. Otherwise, you are potentially indexing out of range of arr1, and arr2, which throws the error. (It's actually undefined behavior, so anything could happen).

answered on Stack Overflow May 14, 2020 by cigien • edited May 14, 2020 by cigien

User contributions licensed under CC BY-SA 3.0