I get a problem
"free(): invalid pointer Process finished with exit code 6"
when I am trying to delete dr[1].
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.
CodePudding user response:
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.