Lucky One
Lucky One

Reputation: 25

Why exception is thrown at the end of this code?

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.

Upvotes: 1

Views: 458

Answers (1)

cigien
cigien

Reputation: 60238

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).

Upvotes: 4

Related Questions