Misc. characters popping up in character strings?

Posted by Dace K on Tue 04 Apr 2006 05:31 PM — 3 posts, 14,027 views.

Canada #0
I have a little piece of code that creates random strings from the following:

char letters[] = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%*(),.;";


with the following:


	buf[0] = '\0';

	max = 3 + (2 * (int)(mob->level / 10));

	for (a=0; a<max; a++)
	{

		temp=number_range(1,strlen(letters)-1);
		buf[a]=letters[temp];
	}
	buf[a+1]='\0';

For some reason, some strings end in untranslatable characters, like upside-down question marks and odd squares.
It shouldn't be left-over junk in the buf char, because I've kind of cleared it with the initial
buf[0] = '\0';


I'm starting to think it's calling some special ascii characters, but since all it's using is !@#$%*(),.;, I don't see why that's happening.

So.. any idea why this is happening?

Thanks :)
Amended on Tue 04 Apr 2006 05:48 PM by Dace K
USA #1
For starters, setting buf[0] to \0 doesn't clear the buffer at all, it just "clears" the string contained in the buffer starting at position 0 (recall the strict definition of a string in C).

Now, here's the thing. You set everything in the interval [a;max[ (that is: a included, max excluded).

When the for loop ends, a = max.

Then you set a+1 to \0.

So you have:
[a;max[ : valid data
max : ???
max+1 : terminating 0

There's your problem. :-)

There are two ways to solve this:
1. properly clear the buffer (silly)
2. set \0 on max, not max+1 (smart)
Canada #2
Tehehe.
Such a silly mistake - thanks for pointing it out man :)