char pointers in lists error

Why doesn't this work? Once I hit enter (cin.get()) I trigger a break point. I can omit line 26 and 29 and have no problems. I can omit line 10, and even with memory leaking at least I don't hit the break point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <list>
using namespace std;

class Word{
private:
	char * word;
public:
	Word() :word(0) {};
	~Word() { delete [] word;}

	void makeWord(char* newWord){
		int length = 0;
		while (newWord[length] != '\0') length++;
		word = new char[length + 1];

		for (int i = 0; i <= length; i++){
			word[i] = newWord[i];
		}
	}

	char* getWord(){return word;};
};

int main(){
	list<Word> myWordList;
	Word myWord;
	myWord.makeWord("hello");
	myWordList.push_back(myWord);
	cin.get();
	return 0;
}


As an error, I get a pop-up window
Windows has triggered a breakpoint in Fun.exe.

This may be due to a corruption of the heap, which indicates a bug in Fun.exe or any of the DLLs it has loaded.


and Visual Studio 2010 opens up crtlib.c.
Last edited on
This is happening because Word doesn't have a valid copy constructor. In the call to push_back, the list gets a copy of myWord. Since you didn't provide a copy constructor, the default is used so this copy would share the same char * word as myWord. When the list gets destroyed, that char * word gets deleted and that same char * word also gets deleted when main finishes (in the destructor of myWord).

Oh, and there are some built-in functions, i.e. strlen and strcpy for doing what you're doing in makeWord.

And you might as well give that object an overloaded assignment operator as well.
Last edited on
Got it working.

Thanks for the explanation, this all makes sense now. As for the class, this is just something I made to display my problem quickly.

Thanks again
Topic archived. No new replies allowed.