Bad ptr error and dynamic memory allocation.

I thought I understood pointers. I really did.

My code so far is designed to read a text file into a series of pointers and then put those pointers into a vector. It does all that fine, but returning that vector from the function gives me an error.
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
33
34
35
36
37
38
39
40
41
vector<string*> v_add() //adds words to the vector
{
	vector<string*> words;
	ifstream in_file;
	in_file.open("C:\\Users\\Michael\\Desktop\\test.txt");
//--------------------------------------------
//check for failure
	if(in_file.fail())
	{
		cout << "Failed to open file." << endl;
		system("pause");
		exit(EXIT_FAILURE);
	}
//--------------------------------------------	
	string current_word;
	string* to_pointer = new string;
	if(in_file >> current_word)
	{
		getline(in_file, current_word);
		to_pointer = &current_word;
		words.push_back(to_pointer);
		//debugging shows that that 'words' successfully stores my file before passing it out.
	}
	in_file.close();
	return words;
}

int main()
{
	vector<string*> text;
	text = v_add();
	int counter = 0;
	while(counter < text.size() - 1)
	{
		cout << *text[counter];
		counter++;
	}
	//I add a break point here in the compiler, and 'text' has the value of 'BadPtr'
	system("pause");
	return 0;
}


I assume that it has something to do with trying to pass my dynamically allocated memory out of the function it's called in, but I'm not too savvy on the rules concerning that.
Topic archived. No new replies allowed.