繁体   English   中英

新到 C 代码不完全明白什么问题

[英]New to C code don't fully understand what's wrong

我使用的代码应该只允许访问密码字节,但它也可以访问字节字节。 我把它从原来的gets改成了fgets,解决了stacksmashing问题。 我需要做什么来解决字节字节被排除的新问题。

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
  
int main(void) {
// Use a struct to force local variable memory ordering
  struct {
    char buff[5];
    char pass;
  } localinfo;
  localinfo.pass = 0;
  
  printf("\n Enter the password:\n");
  fgets(localinfo.buff, 5, stdin); // Get the password from the user
  // Check the password with string matching
  if(strcmp(localinfo.buff, "byte") !=0 ){
    printf ("\n Wrong Password \n");
  }
  else {
    printf ("\n Correct Password\n");
  localinfo.pass = 1; // Set a flag denoting correct password
  }
//IF password matches
// GIVE root or admin rights to user by checking for flag
  if(localinfo.pass){ 
    printf ("\n Congratulations! Root privileges given to the user!\n");
  }
  return 0;
}

fgets()将仅读取您在 size 参数中指定的字节数,对于 null 终止符,减去 1。 所以fgets(localinfo.buff, 5, stdin); 只会读取输入的前 4 个字节。 如果用户输入bytebyte ,则只会将byte读入字符串,并且比较成功。

您应该将输入读入缓冲区的时间长于要与之比较的任何密码。 只有在确定密码有效后才复制到localinfo.buff

另外,不要忘记fgets()如果合适的话,会在输入中留下换行符; 您应该在使用输入之前删除它。 请参阅从 fgets() 输入中删除尾随换行符

你这样声明localinfo.buff

char buff[5];

这意味着该数组只有 4 个字符加上终止 null 字符的空间。

使用输入bytebyte ,该行

fgets(localinfo.buff, 5, stdin);

只会将前 4 个字符读入localinfo.buff并将所有其他字符留在输入 stream 上。 这不是你想要的。

我建议您使用一个可能大小为 200 的输入缓冲区,并通过验证是否找到换行符来验证是否已读入整行。 之后,您应该删除换行符,因为如果输入包含换行符,它将永远不会匹配所需的密码。

这是一个例子:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
  
int main(void)
{
    char line[200], *p;

    //prompt user for input  
    printf("Enter the password: ");

    //attempt to read one line of user input
    if ( fgets( line, sizeof line, stdin ) == NULL )
    {
        printf( "Input error!\n" );
        exit( EXIT_FAILURE );
    }

    //attempt to find newline character
    p = strchr( line, '\n' );

    //verify that entire line was read in
    if ( p == NULL )
    {
        printf( "Line too long for input buffer!\n" );
        exit( EXIT_FAILURE );
    }

    //remove newline character by overwriting it with null character
    *p = '\0';

    //check the password
    if( strcmp( line, "byte" ) != 0 )
    {
        printf( "Wrong Password.\n" );
        exit( EXIT_FAILURE );
    }

    //print success message
    printf( "Correct Password.\n" );
    printf( "Congratulations! Root privileges given to the user!\n" );

    return 0;
}

该程序具有以下行为:

Enter the password: byte
Correct Password.
Congratulations! Root privileges given to the user!
Enter the password: bytebyte
Wrong Password.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM