Home > Enterprise >  How do I deallocate the dynamic memory correctly in this C program? I get a segmentation fault (co
How do I deallocate the dynamic memory correctly in this C program? I get a segmentation fault (co

Time:04-04

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;
}

CodePudding user response:

Array indexes starts at 0 in C . So,

this->listCar[length 1] = car;

should be

this->listCar[length] = car;

Otherwise you don't initialize index 0, but you delete it.

Second problem is with the delete. You should use delete for pointer returned by new and delete[] for new[]. You used new. So,

delete[] listCar[i];

should be

delete listCar[i];

After these 2 changes it looks okay: https://godbolt.org/z/84M1fq1fv

  • Related