Because this has undefined behavior accessing array index out of bound. Array indexing starts from 0
. And here you can't access the 7th index of a 7 element array.
It is strictly prohibited to use gets
- it is even marked deprecated. Complier complained and you ignored it.
Also the initialization would be (here also again compiler threw error when I used your version)
char pass[7] = "alpine" ;// char pass[]="alpine";
You can use fgets
to get input from user.And also there is a function called strcmp
to make the job of comparing strings easy for us. Instead of looping, use that.
if(fgets(str,20,stdin)!=NULL){
str[strcspn(str,"\n")]=0;
if(strcmp(str,pass)==0){
// they matched.
}
}
You can use formatting to make clear interpretation of your program. Saves you from lots of unwanted problems. (Without using strcmp
).
#define LEN 7
...
for (i = 0; i < LEN; i++)
if (pass[i] != str[i]) {
printf("Access denied.\n");
goto label;
} // no else needed
..
Think of what you wrote earlier - in case of mismatch you showed that "Access denied" but when a single character matched then you used break
and it prints "Access granted" - which is not how it should work. You should loop over all the characters available in the password.
But again there is one thing you missed in here - the thing is suppose the password is "alpine"
and you inputted "alpinesssss" - do you want to give him/her access? No. But your program gives - what is the solution here? First whenever you get input password - check whether their lengths match - if not then deny them that moment right away.
So as it turns out, you need to use the strlen
function - but if you are reluctant not to use it you can write the function yourself. (same way you can write strcmp
also).
size_t my_strlen(const char *s){
size_t len = 0;
while(*s++) len++;
return len;
}
Compile the code with all warnings enabled - gcc -Wall -Werror progname.c
.