以下程序中用于字符串比较的分段错误

Segmentation Fault in the Following Program for string comparisons

我遇到以下代码的分段错误。程序的逻辑是它应该接受正确的密码("abcd")并且如果输入任何其他密码它应该拒绝访问,但是我在输入错误的密码后仍然遇到分段错误(例如:"acdc""ancgff")。我在 "abc""xyz" 等密码得到正确的响应,我收到 "access denied" 消息。

请帮助我,我不明白为什么会出现此错误?

#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};
}

你定义

char pin_buf[4];

使用预先确定的 4 大小,然后在不进行任何检查的情况下使用

 strcpy(pin_buf,pin);

pin 有超过 3 个元素(和终止空值)时,您将在尝试复制时超出分配内存的边界,这会导致 undefined behavior.

这就是为什么,你观察

"...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""

也就是说,您根本不需要 pin_buf。您打算执行的操作可以通过 pin 本身完成。