Double free or corruption when using a unique_ptr and inheritance

Viewed 3435

Problem:

Crashing with "double free or corruption" when overwriting the unique_ptr

Setup:

I'm working on a calendar app. I am using SFML which has a class sf::Drawable.
I have a class DayView : public sf::Drawable and a class WeekView : public sf::Drawable. These two classes are the concrete implementations to display the calendar content. One day-wise one week-wise.
In the class CalendarScene I'd like to have a pointer to the current implementation that I can simply replace with a click.
So I place them into an unique_ptr<sf::Drawable> displayImpl to automatically delete them on overwrite.

Now I assign the displayImpl = unique_ptr<WeekView>(new WeekView(...))
If I now press a button an reassign displayImpl = unique_ptr<DayView>(new DayView(...)) the application crashes in the (virtual) destructor of WeekView with the message *** Error in '/home/XXX/workspaces/CDT/XXX/Debug/XXX': double free or corruption (out): 0x0000000000f9ed60 ***

I also have a shared_ptr<vector<shared_ptr<Calendar::Entry>>> as member in either of the *View classes. Don't know if this plays a role.

Where lies my problem?

Code

/*
 * CalendarScene.h
 *
 *  Created on: 17. Nov. 2016
 *      Author: martin
 */

#ifndef SCENES_CALENDARSCENE_H_
#define SCENES_CALENDARSCENE_H_

#include "../Scene.h"
#include "../api/google/GoogleApi.h"
#include "../api/Calendar.h"
#include "../event/Event.h"
#include <vector>
#include <memory>

class CalendarScene: public Scene {
    public:
        CalendarScene(GoogleApi * api);
        virtual ~CalendarScene();

        void prepare(const sf::Vector2u size) override;
        void event(Event &evt) override;

    private:
        void draw(sf::RenderTarget &, sf::RenderStates) const override;
        sf::String texttodisplay;

        std::vector<std::shared_ptr<Calendar>> calendars;
        Calendar::Entries ents;
        Json::Value calendarList;
        Json::Value eventList;

        enum { WEEK, DAY } displayMode;
        int wOffset;

        std::unique_ptr<sf::Drawable> displayImpl = nullptr;

};

#endif /* SCENES_CALENDARSCENE_H_ */

/*
 * CalendarScene.cpp
 *
 *  Created on: 17. Nov. 2016
 *      Author: martin
 */

#include "CalendarScene.h"
#include <SFML/Graphics.hpp>
#include <algorithm>
#include "../ui/SmartText.h"
#include "../ui/UIFactory.h"
#include "../util/sfmladditions.h"

using std::unique_ptr;
using std::shared_ptr;
using std::runtime_error;
using std::time;
using std::time_t;
using std::string;

using io::curl::parameter_map;

using Json::Value;
using Json::ValueIterator;

namespace {

typedef shared_ptr<vector<shared_ptr<Calendar::Entry>>> SharedEntrySharedVector;

enum Format {
    PORTRAIT, LANDSCAPE
};


class WeekView : public sf::Drawable {
public:
    WeekView(SharedEntrySharedVector weekEntries) : ents(weekEntries) {}
    virtual ~WeekView() {}
protected:
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
private:
    SharedEntrySharedVector ents;
};

class DayView : public sf::Drawable {
public:
    int dayOffsetToNow = 0;

    DayView(SharedEntrySharedVector dayEnt) : ents(dayEnt) {}

protected:
    virtual void draw(sf::RenderTarget& target, sf::RenderStates) const;
private:
    SharedEntrySharedVector ents;
};

void WeekView::draw(sf::RenderTarget& target, sf::RenderStates) const {
    /* some drawing */
}

void DayView::draw(sf::RenderTarget& target, sf::RenderStates) const {
    /* some other drawing */
}

} // namespace

CalendarScene::CalendarScene(GoogleApi * api) :
        Scene(api), displayMode(WEEK), wOffset(0), displayImpl(new WeekView(SharedEntrySharedVector())) {
}

CalendarScene::~CalendarScene() {
    calendars.clear();
}

/*
 *
 * Obtain calendar list
 * Obtain event list
 *
 */
#include <iostream>
void CalendarScene::prepare(const sf::Vector2u target) {

    /* populating the ents.entries field which is of type vector<shared_ptr<Calendar::Entry>> */

    displayImpl = unique_ptr<WeekView>(new WeekView(SharedEntrySharedVector(&(ents.entries))));
}

void CalendarScene::event(Event &evt) {
    if (evt.type() == Event::Type::ScreenEvent) {
        /* nothing interesting */
    } else if (evt.type() == Event::Type::ButtonEvent) {
        ButtonEvent &b = (ButtonEvent&) evt;
        switch (b.eventChar()) {
        case sf::Keyboard::Key::W:
            displayMode = WEEK;
            displayImpl = unique_ptr<WeekView>(new WeekView(SharedEntrySharedVector(&(ents.entries))));
            break;
        case sf::Keyboard::Key::T:
            displayMode = DAY;
/********  Here lies the problem  ********/
            displayImpl = unique_ptr<DayView>(new DayView(SharedEntrySharedVector(&(ents.entries))));
            break;
        case sf::Keyboard::Key::Right:
            wOffset++;
            break;
        case sf::Keyboard::Key::Left:
            wOffset--;
            break;
        default:
            return;
        }
        if (wOffset < 0)
            wOffset = 0;
        else if (wOffset > 6)
            wOffset = 6;
        if (displayMode == DAY) {
            ((DayView*)displayImpl.get())->dayOffsetToNow = wOffset;
        }
    }
}

void CalendarScene::draw(sf::RenderTarget &target, sf::RenderStates) const {
    if (!displayImpl)
        return;

    target.draw(*displayImpl);
}

Valgrind says:

==27630== Invalid free() / delete / delete[] / realloc()
==27630==    at 0x4C2A360: operator delete(void*)
==27630==    by 0x4B6D4D: std::_Sp_counted_ptr<std::vector<std::shared_ptr<Calendar::Entry>, std::allocator<std::shared_ptr<Calendar::Entry> > >*, (__gnu_cxx::_Lock_policy)2>::_M_dispose()
==27630==    by 0x411665: std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release()
==27630==    by 0x41054A: std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count() 
==27630==    by 0x4ABDC9: std::__shared_ptr<std::vector<std::shared_ptr<Calendar::Entry>, std::allocator<std::shared_ptr<Calendar::Entry> > >, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr() 
==27630==    by 0x4ABE51: std::shared_ptr<std::vector<std::shared_ptr<Calendar::Entry>, std::allocator<std::shared_ptr<Calendar::Entry> > > >::~shared_ptr()
==27630==    by 0x4A461E: (anonymous namespace)::WeekView::~WeekView() 
==27630==    by 0x4A46B3: (anonymous namespace)::WeekView::~WeekView() 
==27630==    by 0x4AE161: std::default_delete<sf::Drawable>::operator()(sf::Drawable*) const 
==27630==    by 0x4AF7BD: std::unique_ptr<sf::Drawable, std::default_delete<sf::Drawable> >::reset(sf::Drawable*)
==27630==    by 0x4AB181: std::enable_if<std::__and_<std::is_convertible<std::unique_ptr<(anonymous namespace)::DayView, std::default_delete<(anonymous namespace)::DayView> >::pointer, sf::Drawable*>, std::__not_<std::is_array<(anonymous namespace)::DayView> > >::value, std::unique_ptr<sf::Drawable, std::default_delete<sf::Drawable> >&>::type std::unique_ptr<sf::Drawable, std::default_delete<sf::Drawable> >::operator=<(anonymous namespace)::DayView, std::default_delete<(anonymous namespace)::DayView> >(std::unique_ptr<(anonymous namespace)::DayView, std::default_delete<(anonymous namespace)::DayView> >&&) 
==27630==    by 0x4AA445: CalendarScene::event(Event&) 
==27630==    by 0x4DC982: ClientWatch::ClientWatchPrivate::runWindowed() 
==27630==    by 0x4DC6AE: ClientWatch::ClientWatchPrivate::run() 
==27630==    by 0x4DC758: ClientWatch::run()
==27630==    by 0x529CE7: main 
==27630==  Address 0xeb334b0 is 48 bytes inside a block of size 176 alloc'd
==27630==    at 0x4C29180: operator new(unsigned long) 
==27630==    by 0x4E0904: _ZN11ClientWatch18ClientWatchPrivate9makeSceneI13CalendarSceneIRP9GoogleApiEEESt10unique_ptrI5SceneSt14default_deleteIS7_EEDpOT0_ 
==27630==    by 0x4DF88E: _ZN11ClientWatch18ClientWatchPrivate8newSceneI13CalendarSceneIRP9GoogleApiEEEvDpOT0_ 
==27630==    by 0x4DD519: ClientWatch::ClientWatchPrivate::drawFrame() 
==27630==    by 0x4DCB36: ClientWatch::ClientWatchPrivate::runWindowed() 
==27630==    by 0x4DC6AE: ClientWatch::ClientWatchPrivate::run() 
==27630==    by 0x4DC758: ClientWatch::run() 
==27630==    by 0x529CE7: main 
==27630== 

Changing the unique_ptrs to shared ones does not help. Still a double free error.

1 Answers
Related