I'm getting the error "Pointer being freed was not allocated" everytime i want to add an element to a std::map in a storage class. I have added some "couts" in the constructor and destructor to debug and the output is:
new del del
So it seems the destructor is called twice, in the main() and when adding a new Element.
Here is the Code:
Container.h
#include <map>
#include "Element.h"
using std::map;
class Container
{
private:
map<string, Element> storage;
public:
Container();
~Container();
void add(Element e);
void remove(string s);
};
Container.cpp
#include "Container.h"
Container::Container()
{
}
Container::~Container()
{
}
void Container::add(Element e)
{
storage.insert(pair<string, Element>(e.getS(), e)); // CRASH
}
void Container::remove(string s)
{
storage.erase(s);
}
Element.h
#include <iostream>
#include <string>
using namespace std;
class Element
{
private:
string *s;
public:
Element();
Element(string s);
~Element();
string getS();
};
Element.cpp
#include <iostream>
#include "Element.h"
Element::Element()
{
s = new string("std cons");
std::cout << "new" << std::endl;
}
Element::Element(string s2)
{
s = new string(s2);
std::cout << "new" << std::endl;
}
Element::~Element()
{
std::cout << "del" << std::endl;
delete s;
}
string Element::getS()
{
return *this->s;
}
main.cpp
#include <iostream>
#include "Element.h"
#include "Container.h"
int main(int argc, const char * argv[])
{
Element e("l");
Container c;
c.add(e);
return EXIT_SUCCESS;
}