Reputation: 97
I am getting segmentation fault for the following code. The logic of the program that it should accept the correct password ("abcd"
) and it should deny access if entered any other password, but I am still getting a segmentation fault after I enter wrong password (eg: "acdc"
or "ancgff"
).I get proper response for passwords like "abc"
or "xyz"
where I get "access denied" message.
Please help me , unable to understand why I am getting this error?
#include <stdio.h>
#include <string.h>
int check(char *password)
{
char pin_buffer[4];
int authority = 0;
strcpy(pin_buffer,password);
if(strcmp(pin_buffer,"abcd")==0)
authority=1;
return authority;
}
int main(int argc, char *argv[])
{
if(argc < 1)
{
printf(argv[0]);
exit(0);
}
if(check(argv[1]))
{
printf("access granted");
}
else
{
printf("access denied};
}
Upvotes: 0
Views: 63
Reputation: 134346
You define
char pin_buf[4];
with a pre-decided size of 4
and then, without any check, you use
strcpy(pin_buf,pin);
the moment pin
has more than 3 elements (and a terminating null), you'll be overrunning the boundary of allocated memory while attempoting to copy which causes undefined behavior.
That is why, you observe
"...I am still getting a segmentation fault after I enter wrong password (eg:
"acdc"
or"ancgff"
).I get proper response for passwords like"abc"
or"xyz"
"
That said, you don't need the pin_buf
at all. The operations you intend to perform can be done with pin
itself.
Upvotes: 3