Why infinite loop?

Hello.
I appear to have fallen into an infinite loop.Why is it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{
    char buffer[120000] = {0};
    
    int fh = _open(FILENAME, O_RDONLY);
    _read(fh, buffer, 120000 );
    
    
    int i=0;
    char *pc1;
    char *pc2;
    
    pc1 = strstr(buffer, "<context>");
    pc2 = strstr(buffer, "</context>");
    
    while(pc1<=pc2)
       cout << pc1++;
    
    
    while(1);
    
    return 0;
}


Thanks in advance
Print pc1 and pc2 before the loop to see that the values make sense.
Peter, they are both pointers, and their difference is 483.
Ok, so what gets printed in the loop?

I assume you are talking about the loop on line 16-17 because the loop on line 22 is of course an infinite loop because the loop condition is always 1.
while(1); Yep, that's an infinite loop. Unless you mean the loop before that, in which case could you give some example input and output?
I deliberately wrote while(1). I cannot keep up with the text printed.but it seems an infinite loop.
Are you sure that pc1 is less than pc2?
Presumably.
How can I make sure?
Well, now I'm being stupid. Of course pc1 is less than pc2 otherwise it wouldn't have entered the loop.

If you print the content of pc1 and pc2 before the loop, what do you get?
1
2
3
std::cout << "pc1: " << pc1 << std::endl;
std::cout << "pc2: " << pc2 << std::endl;
std::cout << "diff: " << (pc2 - pc1) << std::endl;
The first two statement print text strings. the final statement print 468.
Ahh
cout << pc1++; Will print out characters until it finds '\0'
So everything from pc1 to the end of the buffer will print each iteration of the loop.
See the output from this https://ideone.com/lFW1nV
<context>abc</context>context>abc</context>ontext>abc...
each iteration starts one character deeper.
Edit: You can deference pc1 before printing for a quick fix. cout << *pc1++;
Last edited on
Topic archived. No new replies allowed.