问题
I can't understand why taking the input using fgets always gives me "Wrong password" for my program.
However, when I use gets(), like gets(array); it works.
Expected outputs: when the password is wrong, prints "Wrong Passwor" and for correct one, let me see my "access is granted":
#include <stdio.h>
#include <string.h>
int main(void)
{
int n=15;
char array[n];
int pass = 0;
printf("\n Enter the password : \n");
fgets(array, n, stdin);
if(strncmp(array, "password",n))
{
printf ("\n Wrong Password \n");
}
else
{
printf ("\n Correct Password \n");
pass = 1;
}
if(pass)
{
/* Now Give root or admin rights to user*/
printf ("\n Root privileges given to the user \n");
}
return 0;
}
回答1:
The point here is, fgets() reads and stores the trailing newline, check the man page for fgets().
fgets()reads in at most one less than size characters from stream and stores them into the buffer pointed to bys. Reading stops after anEOFor a newline. If a newline is read, it is stored into the buffer. [...]
You need to remove that trailing newline before the comparison.
You can sanitize the input, using
array[strcspn(array, "\n")] = 0;
to remove the trailing newline from the input.
来源:https://stackoverflow.com/questions/53262648/c-function-fgets-mitigation