Problem with strtok

Started by
5 comments, last by rip-off 16 years, 6 months ago
hey everyone, given the following piece of code

void ParseRecievedMessage(char* buffer)
{
	const char* pch;
	char* lastString;
	pch = strtok (buffer,"#");

	while (pch != NULL)
	{
		lastString = (char*)pch;

		ParseMessage((char*)pch);
		//	printf ("%s\n",pch);
		pch = strtok(buffer, "#");
	}
}

with buffer = Set:ID:3940 why does the loop continue forever? I do use strtok in the ParseMessage() function, but since i'm explicitly asking it to find the tokens in the string afterwords, shouldn't it go "uh oh, no tokens here, lets bail!"?
Advertisement
On the first call to strtok, you need to provide the char* to be tokenized. On subsequent calls, pass NULL. MSDN on strtok.
ok, so what happens if it drops out into that other function and then sets the buffer to be something else? won't i have to reset the strtok to point at buffer since it was pointing at some string in the ParseMessage() function?
See the "Note" on the MSDN page. It's not really possible, unless you enjoy a lot of micromanaging.

Are you using C? If not, convert to a C++ string and parse it as that. If that's a snippet of network-related code, convert to a C++ string. Using C string functions is a security risk.
yeah i was starting to realise I should convert it to a string, I've been using strings and char* mixed throughout the project.


though i'm curious to know, in what way is using c string functions a security risk?
Among other things, they are signifigantly easier to misuse in a fashion that enables buffer exploits.
Quote:Original post by Winegums
yeah i was starting to realise I should convert it to a string, I've been using strings and char* mixed throughout the project.


though i'm curious to know, in what way is using c string functions a security risk?


They are extremely error prone. If for some reason a network message is interpreted without being properly NUL terminated the C library functions will perform reads (or writes, depending on what you are doing) into memory they should not. This allows a malicious use craft a packet that will crash your program, or worse.

C strings are associated with fixed length buffers, which suffer the obvious flaw of stack corruption and arbitrary code execution if not properly handled.

C++ strings are *not* immune to these, as the raw byte data from the network must be safely converted to a std::string instance, and a bug in the conversion can have the same effect. However std::string typically ensures that there should be only one point of failure, this conversion itself. After you have successfully constructed an std::string object it *should* be safe (although you still have to be careful about possible malicious input like cheating attempts).

This topic is closed to new replies.

Advertisement