When I use delete-operator, there is an error : is_block_type_valid(header->_block_use)

Viewed 52

I am writing a simple c++ program that can input people's information and their pet's information. I use a new-operator when I declare the Person struct. There is a Pet struct inside the Person struct and I also use a new-operator to a Pet struct too.

After I execute menu 1 and 2, I thought when I execute menu 3, all of allocated memory will be deleted but it shows me the error is_block_type_valid(header->_block_use).

How can I delete the dynamic allocated memory in this case? I need a help in case 3.

Here's my code:

struct Pet

char PetName[30]; 

int PetAge; 

struct Person

char Name[30]; 

int Age; 

int PetNum;

Pet *PET; 

void InputData(Person *p, int PeopleNum);

static int PeopleNum = 0;

static int PetNum = 0;

void main() :

cout << "Input People Number: ";
cin >> PeopleNum;
Person *Ps = new Person[PeopleNum];

while (1) {
    cout << "\n\n===== Menu =====\n";
    cout << "1. InputData\n" << "2. View List\n" << "3. End\n" << endl;
    cout << "Select Number : ";

    int n = 0;
    cin >> n;

    switch (n) {
    case 1: {
        InputData(Ps, PeopleNum);
        break;
    }
    case 2: {
        for (int i = 0; i < PeopleNum; i++) {
            cout << "\n==========================\n";
            cout << "Peole["<<i+1<<"] Name: " << Ps->Name << "   Age: " << Ps->Age << endl;
            cout << "==========================\n";
            for (int j = 0; j < Ps->PetNum; j++) {
                cout << "Pet[" << j + 1 << "] Name: " << Ps->PET->PetName << "   Age: " << Ps->PET->PetAge << endl;
                Ps->PET++;
            }
            Ps++;
        }
        cout << "==========================\n";
        break;
    }
    case 3: {
        for (int i = 0; i < PeopleNum; i++) {
            for (int j = 0; j < Ps->PetNum; j++) {
                delete[](Ps->PET);
                Ps->PET++;
            }
            delete[]Ps;
            Ps++;
        }

        cout << "\nEnd the programm" << endl;
        return 0;
    }
    default:
        break;
    }
}

*void InputData(Person p, int PeopleNum) :

for (int i = 0; i < PeopleNum; i++) {
    cout << "\nInput *" << i + 1 << "'s Name and Age.\n";
    cout << "Name : ";
    InputValue(p->Name);
    cout << "Age : ";
    InputValue(p->Age);

    cout << "Input Pet Number: ";
    InputValue(p->PetNum);
    PetNum = p->PetNum;

    p->PET = new Pet[p->PetNum];

    cout << "\n\n\n* Input Pet's name and age.\n";
    
    for (int j = 0; j < p->PetNum; j++) {
        cout << "Pet's Name : ";
        InputValue(p->PET->PetName); 
        cout << "Pet's Age : ";
        InputValue(p->PET->PetAge);
        cout << "\n";

        p->PET++;
    }
    for (int j = 0; j < p->PetNum; j++) {
        p->PET--;
    }
    p++;
}
0 Answers
Related