lundi 4 avril 2022

How do I deallocate the dynamic memory correctly in this C++ program? I get a segmentation fault (core dump) when I execute the program

How do I deallocate the dynamic memory correctly in this simple C++ program? I get a segmentation fault (core dump) when I execute the program. I am trying to find out where I went wrong. Thanks in advance.

I am trying to add dynamically allocated objects to an array and am trying to get the destructor to clear the memory. I am unsure if I have created the destructor correctly in carList.

#include <iostream>

#define MAX 3

class Car{

    public:
        Car(std::string name){
            this->name = name;
        }

        ~Car(){
        }

        std::string getName(){
            return this->name;
        }

    private:
        std::string name;
};


class carList{
    public:
        carList(){
            this->length = 0;
        }

        ~carList(){
            //the deconstructer; I am unsure If I have implemented it correctly
            for (int i = 0; i < this->length; i++)
            {
                if(listCar[i] != nullptr){
                delete[] listCar[i];
                }
            } 
                
        }

        int getLength(){
            return this->length;
        }
        // adding to the end of the list, unsure whether Implemented correctly
        void addEndList(Car* car){  //???
                if(this->length < MAX){
                this->listCar[length+1] = car;
                this->length++;
                }
        }

    private:
        Car* listCar[MAX]; 
        int length;
};

int main(){
    carList* carlist = new carList();

    std::cout << carlist->getLength() <<std::endl;

    Car* car2 = new Car("one");
    Car* car3 = new Car("two");

    carlist->addEndList(car2);
    carlist->addEndList(car3);

    std::cout << carlist->getLength() <<std::endl;
    
    std::string name1 = car2->getName();
    std::cout << name1 << std::endl;

    delete carlist;  // deleting the carlist, unsure if I need to delete car2, 
                      //and car3 or if the destructor handles that, which I am 
                      //trying to implement
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire