Skip to content

Instantly share code, notes, and snippets.

@dayjaby
Created February 15, 2022 14:56
Show Gist options
  • Save dayjaby/792d80b409ab15d198ea42490c330346 to your computer and use it in GitHub Desktop.
Save dayjaby/792d80b409ab15d198ea42490c330346 to your computer and use it in GitHub Desktop.
Illarion Player Content Bug
#include <map>
#include <iostream>
class Container {
public:
Container(int i) : _i(i) {
std::cout << _i << " constructed" << std::endl;
}
~Container() {
std::cout << _i << " destructed" << std::endl;
}
int _i;
};
int main() {
std::map<int, Container*> depots;
std::map<int, Container*> depotContents;
depotContents[0] = new Container(1);
depots[0] = new Container(2);
bool dataOk = false;
if (!dataOk) {
for (auto const& depot : depots) {
auto depotIt = depotContents.find(depot.first);
if (depotIt != depotContents.end()) {
depotIt->second = depot.second;
}
}
}
for (auto rit = depots.rbegin(); rit != depots.rend(); ++rit) {
std::cout << "Trying to delete container " << rit->second->_i << std::endl;
delete rit->second;
}
for (auto rit = depotContents.rbegin(); rit != depotContents.rend(); ++rit) {
std::cout << "Trying to delete container " << rit->second->_i << std::endl;
delete rit->second;
}
return 0;
}
#include <map>
#include <iostream>
class Container {
public:
Container(int i) : _i(i) {
std::cout << _i << " constructed" << std::endl;
}
~Container() {
std::cout << _i << " destructed" << std::endl;
}
int _i;
};
int main() {
std::map<int, Container*> depots;
std::map<int, Container*> depotContents;
depotContents[0] = new Container(1);
depots[0] = new Container(2);
bool dataOk = false;
if (!dataOk) {
for (auto const& depot : depots) {
auto depotIt = depotContents.find(depot.first);
if (depotIt != depotContents.end()) {
// prevent memory leak
if (depotIt->second) delete depotIt->second;
depotIt->second = depot.second;
}
}
}
// delete first the contents
for (auto rit = depotContents.rbegin(); rit != depotContents.rend(); ++rit) {
// only delete if not present also in depots
auto depotIt = depotContents.find(rit->first);
if (depotIt == depotContents.end()) {
delete rit->second;
}
}
for (auto rit = depots.rbegin(); rit != depots.rend(); ++rit) {
delete rit->second;
}
return 0;
}
$ g++ broken.cpp -o broken && ./broken
1 constructed
2 constructed
Trying to delete container 2
2 destructed
Trying to delete container 0
0 destructed
free(): double free detected in tcache 2
Abgebrochen (Speicherabzug geschrieben)
$ g++ fixed.cpp -o fixed && ./fixed
1 constructed
2 constructed
1 destructed
2 destructed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment