删除地图中的指针会导致内存错误

时间:2018-03-20 16:16:14

标签: c++

我有三个类来表示数据库数据。一个UserRow一个HobbyRow和一个UserAndHobbyRow合并UserRow,其中包含一个HobbyRow,但地图为X new。我得到UserRow,然后我得到X HobbyRows并将其添加到UserAndHobbyRow中的地图。我可以把它打印出来。但是当我去释放地图数据时,我收到了内存错误。

请注意,这是一个用于说明问题的小型模型。建议不使用#include <iostream> #include <sstream> #include <map> #include <string> class UserRow { public: unsigned int id; std::string name; void Print(); UserRow(); ~UserRow(); }; UserRow::UserRow(){} UserRow::~UserRow(){} void UserRow::Print(){ std::cout << " -- User Row -- " << std::endl; std::cout << this->id << std::endl; std::cout << this->name << std::endl; } class HobbyRow { public: unsigned int id; unsigned int userId; std::string hobby; void Print(); HobbyRow(); ~HobbyRow(); }; HobbyRow::HobbyRow(){} HobbyRow::~HobbyRow(){} void HobbyRow::Print(){ std::cout << " -- Hobby Row -- " << std::endl; std::cout << this->id << std::endl; std::cout << this->userId << std::endl; std::cout << this->hobby << std::endl; } class UserAndHobbyRow { public: UserRow *userRow; std::map<int, HobbyRow*> hobbyMap; void Print(); UserAndHobbyRow(); ~UserAndHobbyRow(); }; UserAndHobbyRow::UserAndHobbyRow(){} UserAndHobbyRow::~UserAndHobbyRow(){} void UserAndHobbyRow::Print(){ std::cout << " -- User And Hobby Row -- " << std::endl; this->userRow->Print(); std::map<int, HobbyRow*>::iterator it; for(it = this->hobbyMap.begin(); it != this->hobbyMap.end(); it++){ it->second->Print(); } } int main() { UserRow userRow; userRow.name = "My Name"; userRow.id = 0; HobbyRow *hobbyRow = new HobbyRow[2]; hobbyRow[0].id = 0; hobbyRow[0].userId = 0; hobbyRow[0].hobby = "sports"; hobbyRow[1].id = 1; hobbyRow[1].userId = 0; hobbyRow[1].hobby = "cooking"; UserAndHobbyRow userAndHobbyRow; userAndHobbyRow.userRow = &userRow; for(unsigned int i = 0; i < 2; i++){ userAndHobbyRow.hobbyMap.insert(std::make_pair(hobbyRow[i].id, &hobbyRow[i])); } userAndHobbyRow.Print(); std::map<int, HobbyRow*>::iterator it; for(it = userAndHobbyRow.hobbyMap.begin(); it != userAndHobbyRow.hobbyMap.end(); it++){ delete it->second; // memory free error } return 0; } 这不是答案,因为这是一个简化的例子。然而,完全相同的是,所有内容都处于相同的函数上下文中。

WalletViewController

https://onlinegdb.com/Sy-KX20Ff

1 个答案:

答案 0 :(得分:2)

您使用new为hobbyRow分配内存

HobbyRow *hobbyRow = new HobbyRow[2];

你需要删除整个数组

delete[] hobbyRow;

目前您执行以下操作:

delete &hobbyRow[0];
delete &hobbyRow[1];