Strange command line argument behaviour

I have this code which is supposed to convert an URL to the form in which it is used in a DNS request:

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
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
	char question[256];
	char url[256];
	char *p = argv[1];
	char *temp;
	int curPos = 0;
	int curLen = 0;
	
	do {
		curLen = 0;
		temp = p;
		while (*p != '.' && *p != 0) {
			++p;
			++curLen;
		}
		question[curPos] = curLen;
		++curPos;
		while (temp != p) {
			question[curPos] = *temp;
			++temp;
			++curPos;
		}
		++p;
	} while (*p != 0);
	question[curPos] = 0;
	printf("%d\n", strlen(question));
	
	p = question;
	while (*p != 0) {
		if (*p < 20) printf("%d", (int) *p);
		else printf("%c", *p);
		++p;
	}
	printf("\n");
	
	return 0;
}


For some reason it is acting very strangely. Sometimes it gives me the correct output and sometimes it doesn't. For example, if the executable is abc.exe, when I run it like this from the command line (on Windows):
abc qwe.rtyui.op.as

I get this output:
156
3qwe5rtyui2op2as6m-448B<248-56Z3-16Z3 Z3-120Z3-56Z3-24Z3< Z3h Z3-120 Z3-88 Z3-32 Z38!Z3 !Z3@!Z3-64!Z38"Z3-40"Z316#Z30#Z3P#Z3h#Z3-56%Z316&Z38&Z3-120&Z3-88&Z3-56&Z3-16&Z3<'Z30'Z3-128'Z3-96'Z3-32'Z

However, if I run it like this:
abc.exe qwe.rtyui.op.as

I get this output:
16
3qwe5rtyui2op2as

The second of which is the expected output.

If I strcpy() argv[1] into a separate string, sometimes I got the path to the program mixed in with the output, for example:
3qwe5rtyui2op2as1V1o1l1u1m1e1\1U1s1e1r1s1\1M1a1t1t1\1D1e1s1k1t1o1p1
Which is the path the the program with 1s in between every character.

The output varies depending on what I type at the command line. Any help would be appreciated.
Last edited on
Have you tried debugging it? You really should give it a try.
Line 27 will produce a buffer overflow on line 28 when the loop from line 16 breaks because !*p.
Thanks helios, can't believe I didn't spot that after staring at my screen for so long.

Thank you both for your suggestions.
Topic archived. No new replies allowed.