使用unique_ptr和继承时双重释放或损坏

Double free or corruption when using a unique_ptr and inheritance

本文关键字:释放 损坏 继承 unique ptr 使用      更新时间:2023-10-16

问题:

覆盖unique_ptr时因"双重释放或损坏"而崩溃

设置:

我正在开发一个日历应用程序。我正在使用具有类sf::Drawable的SFML。
我有一个班级DayView : public sf::Drawable和一个班级WeekView : public sf::Drawable。 这两个类是显示日历内容的具体实现。一天一周。
在类CalendarScene中,我希望有一个指向当前实现的指针,我可以通过单击简单地替换它。
因此,我将它们放入unique_ptr<sf::Drawable> displayImpl中,以便在覆盖时自动删除它们。

现在我分配displayImpl = unique_ptr<WeekView>(new WeekView(...))
如果我现在按下一个按钮,重新分配displayImpl = unique_ptr<DayView>(new DayView(...))应用程序在WeekView的(virtual)析构函数中崩溃

,并显示消息*** Error in '/home/XXX/workspaces/CDT/XXX/Debug/XXX': double free or corruption (out): 0x0000000000f9ed60 ***

我还有一个shared_ptr<vector<shared_ptr<Calendar::Entry>>>,是*View类中的任何一个成员。不知道这是否起作用。

我的问题在哪里?

法典

/*
* 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);
}

瓦尔格林德 说:

==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== 

unique_ptr更改为shared无济于事。仍然是一个双重免费错误。

我相信您可能正在复制此对象并将其删除到其他地方。 std::unique_ptr<>应该能够处理你提到的情况。以这个为例,它工作正常:

#include <memory>
#include <iostream>
struct A {
int a;
A( int v ) : a(v) {}
};
int main() {
std::unique_ptr<A> p( new A(1) );
p = std::unique_ptr<A>( new A(3) );
std::cout << "A:" << p->a << "n";
return 0;
}

然后运行

$ clang++ -std=c++11 testUniquePtr.cpp -o testUniquePtr
$ ./testUniquePtr 
A:3

但是,如果您获取指针并分配给另一个unique_ptr,例如

int main() {
std::unique_ptr<A> p( new A(1) );
std::unique_ptr<A> q( p.get() );
std::cout << "A:" << p->a << "n";
return 0;
}

然后你得到一个双倍免费:

$ ./testUniquePtr 
A:1
*** Error in `./testUniquePtr': double free or corruption (fasttop): 
0x0000000001258c20 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f1ce28367e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x7fe0a)[0x7f1ce283ee0a]