简体   繁体   中英

Why does printing input buffer result in unexpected output?

In the following code, whenever the same string is input in arrays "pass" and "repass", the string in "repass" gets doubled. For example, if the input string in "pass" and "repass" are aaaaaaaa then the string in "repass" becomes aaaaaaaaaaaaaaaa because of which strcmp() gives a negative answer.

Can somebody help and explain the reason behind this?

#include<stdio.h>
#include<conio.h>
#include<string.h>

void main()  
{  
    char user_name[20],pass[8],repass[8];  
    int i=0,c=0,tr=1;//tr for no of try(should less than 3 )  
    clrscr();  
    puts("enter user name");  
    gets(user_name);  
    printf("\n\n\n\n");  

    for(tr=1;tr<=3;tr++)  
    {  
        puts("\n\nenter password");  

        while(i<8)  
        {  
            pass[i] = getch();  
            putchar('*');  
            i++;  
        }  

        printf("\n\n\n\nplease reenter the password\n\n");  
        i=0;  

        while(i<8)  
        {  
            repass[i]=getch();  
            putchar('*');  
            i++;  
        }  

        c=strcmp(pass, repass);  
        printf("c=%d", c);  

        if(strcmp(pass,repass)==0)  
            c=0;  
        else  
            c++;  

        if(c==0)  
        {  
            printf("\n\n\t****\vsuccessful login*********** ");  
            break;  
        }  
        else  
            printf("\n\nsorry password did not match");  
    }  

    if(tr>3)  
        puts("\n\nlogin failed");  
    //printf("%s        %s",pass,repass);  
    getch();  
}

You're not 0-terminating your strings so using "string" functions on them (printing with "%s", strcmp, etc) is illegal.

In this particular case it looks as repass is "doubled" because of the stack layout, the way pass and repass are one next to the other.


Side node, use fgets instead of gets .

There's a few things wrong here.

  1. Don't use gets. Gets is insecure. Get out of the habit of using it. Use scanf instead.
  2. You're not null-terminating your strings. Strings require a '\\0' at the end to signal that they're done.
  3. Please format your code better. It will help you follow the logic if you do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM