Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How delete int* dynamic array?

I get a problem

"free(): invalid pointer
Process finished with exit code 6"

when I am trying to delete dr[1].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please say why there is the error in current input (str1, str2)?
”’

#include <iostream>

using namespace std;

int64_t myMin(int64_t first, int64_t second) {
    return first > second ? first : second;
}

int main() {
    string str1, str2;
    str1 = "ABRA", str2 = "CADABRA";
    int64_t n1 = static_cast<int64_t>(str1.length()), n2 = static_cast<int64_t>(str2.length());
    int64_t **dp = new int64_t *[n2 + 1];
    for (int i = 0; i <= n2; ++i) {
        dp[i] = new int64_t[n1 + 1];
        dp[i][0] = 0;
        dp[0][i] = 0;
    }
    for (int64_t i = 1; i <= n2; ++i) {
        for (int j = 1; j <= n1; ++j) {
            if (str2[i - 1] == str1[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = myMin(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    cout << dp[n2][n1];
    cout << '\n' << n2 << "\t" << n1 << '\n';
    for (int i = n2; i >= 0; --i) {
//  There is no problem with uncommented below line. Why?
//        if (i != 1)
        delete[] dp[i];
    }
    delete[] dp;
    return 0;
}

”’

I use CLion framework.

>Solution :

dp[0][i] = 0;

When n2 > n1, this will write over the array dp[0] as i grows.

Adding a bound-check will fix this problem:

if (i <= n1)
    dp[0][i] = 0;

In addition, I’d strongly recommend to learn how to debug program.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading