c - C 中比较空字符串的结果

标签 c arrays null comparison string-comparison

我在 C 程序中有两个字符数组:

char stored_pass[15] = "steveone"
char pass[15] = "\0" 

当运行 strcmp(stored_pa​​ssword, pass) 来比较两者时,我得到的结果是它们相等 (==0)。

我不太明白为什么会这样。

谁能给我解释一下吗?我查找了空字符串和以 null 结尾的字符串之间的区别,但没有真正找到答案。

问题似乎出在身份验证方法中。

整个C程序的源代码:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

// Execute any shell command
void execute(char *cmd)
{
   execl("/bin/bash", "bash", "-p", "-c", cmd, NULL);
}

void sanitise(char *password)
{
  int i,j;
  char tmp[15];

  // remove non-alphabet  characters from passwords
  j=0;
  for(i=0; i < 15; ++i) 
    if(password[i] >= 'a' && password[i] <= 'z') {
      tmp[j]=password[i];
      ++j;
    } else break;
  tmp[j] = '\0';

  strcpy(password, tmp);

}

int authenticate(char *str)
{
  char stored_password[15]="";
  char pass[15];
  char path[128] = "/etc/computer/Steve/password";
  int i;

  FILE *fpp; 
  int auth=0;

  fpp = fopen(path, "r");

  if(fpp == NULL)
  {
     printf("Password file %s not found\n", path);
     exit(1);
  }

  fgets(stored_password, 15, fpp);
  sanitise(stored_password);

  strcpy(pass, str);
  sanitise(pass);

  if(strcmp(stored_password,pass) == 0)
     auth=1;
  else {
     auth=0;
  }

  fclose(fpp);

  return auth; 
}

int main(int argc, char* argv[], char *envp[])
{
  if(argc < 2) 
  {
    printf("Usage: %s password\n", argv[0]);
    return 0; 
  }


  if(!authenticate(argv[1])) {
    // Log all failed attempts
    printf("Wrong password. This incident has been logged.\n");
    execute("/home/Steve/Public/error.sh"); 
    return 0;
  }

  execute("cat /etc/computer/Steve/secret");

  return 0;
}

最佳答案

首先,您的清理函数在第一次找到非字母字符值时会放置一个 '\0' ,从而终止字符串。您确定这是您想要的吗?(也许您想在 for 循环中使用 continue; 而不是 break; ?)如果文件中的密码和用户输入的密码都以数字开头,则比较的字符串都将等于“\0”。如前所述,尝试在 strcmp() 调用之前打印两个字符串。

关于c - C 中比较空字符串的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58254001/

相关文章:

c - 尝试创建一个 C 程序来打印出所有具有有理平方根的数字?

c - 使用 qsort 对 C 中的字符串数组进行排序时出现段错误

java - 为什么静态对象作为参数传递给另一个类的构造函数时为 null

java - 如何从二维数组中删除空值?

c - 什么时候在 GNU C 中使用分离线程?

union 中的 C 对齐

c++ - 根据第三个整数的符号快速加/减两个整数

java - 删除对象后更新数组列表

Java - 将字符串与字符串数组进行匹配

sql - 在 Oracle DB 中使用 LISTAGG 时,如何从字符串中删除 CHR(0)?