dimanche 30 juillet 2023

Why does following code free memory more than allocated?

Here is my code:

#include <iostream>
using namespace std;

int* NextVal(char str[], int size) {
    int i = 0, j = -1;
    int *nextVal = new int[size];
    nextVal[0] = -1;
    while (i < size) {
        if (j == -1 || str[i] == str[j]) {
            ++j; ++i;
            nextVal[i] = j;
            if (str[i] == str[j]) nextVal[i] = nextVal[j];
        }
        else j = nextVal[j];
    }

    return nextVal;
}

int main() {
    char str[] = { "abaab" };
    char* str0 = new char[100];
    cin >> str0;
    int size = strlen(str);
    int* nextVal = NextVal(str, size);
    delete []nextVal;
    int i = 0, j = 0, size0 = strlen(str0);
    while (i < size0) {
        if (j == -1 || str0[i] == str[j]) {
            ++i; ++j;
        }
        else j = nextVal[j];
    }
    if (i == size0 && j != size) cout << "false";
    else cout << i - size << "\n";
    cout << sizeof(nextVal);
    delete []str0;
    delete nextVal;
}

It is KMP. The last statement report following error: enter image description here

The same error will get if I put the last statement like

int NextVal (){
  while(...){
  ...}
  delete [] nextVal;
  return nextVal;
}

So what is the point? I can free str0 correctly,there is no difference in my opoinion. Why after the while statement nextVal has space more I have allocated?

Aucun commentaire:

Enregistrer un commentaire