Problems with char*

I have this function that puts characters into a char* until it reaches a empty space or invalid character. The problem is that it works, well mostly... except I get really WEIRD extra "luggage" at the end of the string everytime I put it on display with cout. Its really irritating and I'm not sure what the problem is.

DefaultValidator is a function that basically returns true or false. My main purpose for this function is to return false if there is a space ' ' in the text file that I am parsing.

The end result of this function SHOULD be just '100', but it returns '100' plus extra junk.

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
char *GetNextToken(char *buffer, int *index) {
	vector<char> temp;
	int i = *index;

	// Skip any spaces
	while (DefaultValidator(buffer[i]) == false) {
		i++;
	}

	while (DefaultValidator(buffer[i])) {
		temp.push_back(buffer[i]);
		i++;
	}


	// Convert the vector to a usuable string
	char *word = new char[temp.size()];
	int g = 0;
	while (g < temp.size()) {
		word[g] = temp[g];
		g++;
	}
	Sleep(2000);
	return word;
	delete[] word;
}


This is the link to a screen shot of the problem, youll see it on the last line of text.

http://img52.imageshack.us/i/73833529.jpg/

Please, can anyone help me figure this out?
C-style strings have to be null terminated (with a '\0' or 0 character.). That's how the computer knows it found the end of the string. Without it, it will keep printing whatever garbage follows the string data until it happens to stumble across a null.

You also are leaking memory:

1
2
3
	return word;  // once you return, the function stops here
	delete[] word;  // so word is never deleted
}


But all of this can be avoided if you use string to represent a string instead of an error-prone char array.

Your function, simplified and without memory leaks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string GetNextToken(char *buffer, int *index) {
	string word;
	int i = *index;

	// Skip any spaces
	while (DefaultValidator(buffer[i]) == false) {
		i++;
	}

	while (DefaultValidator(buffer[i])) {
		word.push_back(buffer[i]);
		i++;
	}

	Sleep(2000);
	return word;
}
Topic archived. No new replies allowed.