简体   繁体   中英

Dynamic allocation of memory (Array of pointers)

is there a memory leak in this operator overloading ?

My thinking is below the code.. (MotorVehicle is a class with no allocation)

class myClass{    
private:
    MotorVehicle **vehicle;
    int vehNo;
public:

myClass() : vehicle(), vehNo(0){ } // vehicle() -> NULL

    ~myClass()
    {
        for(int i = 0; i < vehNo; i++)
            delete vehicle[i];
    }
    .
    .
    .
    myClass &operator+=(MotorVehicle *veh)
    {
        MotorVehicle **temp = new MotorVehicle*[vehNo + 1];
        for(int i = 0; i < vehNo; i++)
            temp[i] = vehicle[i];
        temp[vehNo] = veh;
        //for(int i = 0; i < vehNo; i++)
          //  delete vehicle[i];
        vehNo++;
        vehicle = new MotorVehicle*[vehNo];
        for(int i = 0; i < vehNo; i++)
            vehicle[i] = temp[i];

        return *this;
    }
};

I have array of pointers of type MotorVehicle (**tmp) for which I have allocated memory and set every single one of them to point to what a vehicle is pointing to + last one to point to what veh was pointing to. Since I set them to point to what vehicle was pointing I wont lost the data somewhere and can deallocate them in the future. Then I allocated memory for vehicle again to return them to point to +1 object. However I'm allocating memory two times and both contain the location of same thing, so If i delete one of them then the other won't have anything in it (will hang somewhere).. But at the end the memory will get deleted with the destructor ? Am I thinking right? How to get around allocating memory 2 times for the same thing?

Ps yeah manually :# (Any materials which might help me in any way would be greatly appreciated)

Yes, you're leaking temp .

A better try:

myClass &operator+=(MotorVehicle *veh)
{
    MotorVehicle **temp = new MotorVehicle*[vehNo + 1];
    for(int i = 0; i < vehNo; i++)
        temp[i] = vehicle[i];
    temp[vehNo] = veh;
    vehNo++;
    delete[] vehicle;
    vehicle = temp;

    return *this;
}

An even better solution: Use std::vector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM