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

问题描述 投票:-1回答:1

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

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

[运行strcmp(stored_password, 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;
}
c arrays null comparison string-comparison
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.