mercredi 1 mars 2017

Local variables and dynamic memory allocation. Smart pointers [duplicate]

This question already has an answer here:

Profiling our project I have found poor code and I need to suggest best solution. I deliberately simplified the code for ease of understanding. The situation is the following:

struct TResource {};
typedef std::vector<TResource*> TResources;

struct TProgramm
{
    // Comment destructor to reproduce memory leaks
    ~TProgramm()
    {
        for(auto r : _resources)
        {
            delete r;
            r = nullptr;
        }
        _resources.clear();
    }

    TResources _resources;
};

struct TEpgSchedule
{
    TProgramm _program;
};
typedef std::vector<TEpgSchedule> TEpgSchedules;

void getEpgSchedules(TEpgSchedules& epg_schedules)
{
    TEpgSchedule epg_schedule; //crash code
    TResource* resource = new TResource();

    epg_schedule._program._resources.push_back(resource);
    epg_schedules.push_back(epg_schedule);
}

int main(int , char **)
{
    TEpgSchedules epg_schedules;
    getEpgSchedules(epg_schedules);
    // Doing more things with epg_schedules....

    return 0;
}

Initial problem was in memory leaks. To resolve it I have added destructor to the TProgramm struct. I have told myself - good job - but after running of my application I have received crash. After investigation of this new issue I found code labeled in my code as 'crash code'. It is clear that after adding destructor to the Programm struct my main function does the following:

  1. Create local variable epg_schedule in getEpgSchedules() function;
  2. Create new TResource and push it to the resources of the programm;
  3. Calling TEpgSchedule copy constructor for line epg_schedules.push_back(epg_schedule);
  4. Delete epg_schedule and its resources on getEpgSchedules() exit;
  5. Repeatedly deleting epg_schedulesom main() exit - crash!!!

Could you suggest how to refactor this code to avoid memory leaks and crashes?

Aucun commentaire:

Enregistrer un commentaire