0

I have a problem inserting into std::map and a class like this:

class Dat
{
private:
    char* data;

public:         
    Dat():data(NULL){}  
    ~Dat() { if(data) delete[] data; }  
    const char* get() { return data; }

    void set(char* str)
    {       
        if(!str) return;
        data = new char[strlen(str)+1];
        strcpy(data, str);
    }   
};

which I trying to use like this:

int main()
{   
    map<int, Dat> mDat;
    Dat dat;    

    dat.set("hello");
    mDat.insert(pair<int, Dat>(0, dat));
    printf("%s\n", mDat[0].get());
    return 0;
}

And the problem is:

before insert: data=0x0063a728 "hello"  
after insert:  data=0x0063a728 "îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþOµ?bí\a" 
after printf:  data=0x0063a728 "««««««««"

Can't find out why data becomes garbage.

  • 7
    You're missing a copy-constructor. And you might want to read about [the rule of three](http://en.cppreference.com/w/cpp/language/rule_of_three). Hint: When the `dat` object is copied, the *pointer* is copied and not what it points to, guess what happens when the destructor of one copy is called. – Some programmer dude Feb 15 '15 at 15:06
  • Your output is 0xfeeefeee ... which is a magic debug code to mark freed heep memory: http://stackoverflow.com/a/127404/487892 @JoachimPileborg covered the reason for this. – drescherjm Feb 15 '15 at 15:10

1 Answers1

0

The default copy constructor generated for you is doing a shallow copy.

Define a copy constructor that does a deep copy and it'll fix your issue

Kam
  • 5,878
  • 10
  • 53
  • 97