Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete array pointer?

How do I delete the memory that have been allocated for array models, names? I tried every method but it always crashes when I run it.

int main()
{

    vector<Person*> people;

    const int PERSON_SZ = 4;
    char * names[] = {"Jim", "Fred", "Harry", "Linda"};
    int ages[] = { 23, 35, 52, 59 };

    for (int i = 0; i < PERSON_SZ; i++)
    {

        Person * temp = new Person(names[i], ages[i]);
        people.push_back(temp);
    }

    // A vector of Car pointers
    vector<Car*> cars;

    const int CAR_SZ = 3;
    char * models[] = { "Festiva", "Ferrarri", "Prius" };
    srand(time(0));
    for (int i = 0; i < CAR_SZ; i++)
    {

        Car * temp = new Car(models[i]);
        temp->set_driver(people[rand() % (people.size())]);
        temp->set_owner(people[rand() % (people.size())]);
        cars.push_back(temp);
    }



    for (int p = 0; p < people.size(); p++)
    {
        people[p]->increment_age();
    }

    for (int c = 0; c < cars.size(); c++)
    {
        cars[c]->print();
    }

    delete [] names;
    for ( int r = 0; r < CAR_SZ; ++r )
       {
           delete [] models[r];
       }
    return 0;
}
like image 249
Richard Nguyen Avatar asked Dec 28 '25 16:12

Richard Nguyen


1 Answers

You didn't allocate models and names using new, so you cannot delete them.

Both arrays are allocated on the stack and are automatically deleted, when the function returns.

The contents of the (string) arrays (i.e. the strings itselves) are stored in the global data segment and cannot be freed at all. This would also be dangerous because the compiler might use the same string constant at different places in the program.

like image 137
MartinStettner Avatar answered Dec 31 '25 06:12

MartinStettner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!