Rishabh Shah
Rishabh Shah

Reputation: 25

While loop not working properly in C

The loop in this program unexpectedly fails to terminate. When I test with inputs t=4 and s="qi", the value of t that gets printed when the program runs is 0 rather than the expected value 4. What's going wrong?

#include<stdio.h>

int main()
{
    int t,flag=0;
    char s[2];
    scanf("%d ",&t);
    while(t)
    {
        scanf("%s",s);
        if(s[1]=='i')
        {
            if(flag==0)
                flag=1;
            else
                flag=0;
        }
        else if(s[1]=='b')
        {

        }
        else if(s[1]=='r')
        {

        }
        printf("%d\n",t);
        t=t-1;
    }
}

Upvotes: 0

Views: 150

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

The problem is that you are overwritting memory beyond array char s[2]; When you enter "qi" with scanf then there is stored three characters that is the terminating zero is appended to characters "qi". This terminating zero overwrites memory occupied by t. Enlarge array s at least as

char s[3].

Also it would be better to use a for loop then the while loop in this case

for ( ; t; --t )

because it is difficult to see that t is changed at the end of the while loop.

Upvotes: 0

2501
2501

Reputation: 25752

Array s has the size of 2. This means it can hold only one character. You input two characters, "qi", and the null terminator is written in adjacent memory, overwriting whatever is there.

This will cause undefined behaviour. You got unlucky and apparently overwritten the first byte of variable t, which will set it to 0( in your case ) on a little endian machine.

The solution is to enlarge the string to at least 3 elements, and restrict the input in scanf() to a maximum of two characters.

Upvotes: 2

user3574816
user3574816

Reputation: 1

One obvious syntactical error I noticed was:

printf("%d\n");

should be

printf("%d\n",t);

Since I Suppose you Wish to print the value of t at every iteration.

Upvotes: 0

Abhi
Abhi

Reputation: 744

Since your character array is of size 2 and your input string "qi" will need 3 characters including a null, which causes overflow. Due to this your program terminates abruptly.

Upvotes: 0

Related Questions