c++ Buffer Overflow, strcpy, fgets, sprintf显示运行时错误


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check_authentication(char* password) {
int auth_flag = 0;
char* password_buffer;
char* dept;
password_buffer = (char*)malloc(16);
dept = (char*)malloc(10);
printf("Your department?");
fgets(dept, 10, stdin); //line 11
strcpy_s(password_buffer, 16, password); //line 12
if (strcmp(password_buffer, "AsiaPacificInst") == 0) {
if (strcmp(dept, "NSF") == 0) {
auth_flag = 1;
}
}
if (strcmp(password_buffer, "AsiaPacificUni") == 0) {
if (strcmp(dept, "TM") == 0) {
auth_flag = 1;
}
}
return auth_flag;
}
int main(int argc, char* argv[]) {
char errmsg[512];
char outbuf[512];
char user[20];

printf("Username: ");
fgets(user, 20, stdin); //line 32
if (strcmp(user, "Adm1n") == 0) {
printf("Authorised Usern"); sprintf_s(errmsg, "Authorised User %400s", user); sprintf_s(outbuf, errmsg);  //line 34
if (argc < 2)
{
printf("Usage: %s <password>n", argv[0]); exit(0);
}
if (check_authentication(argv[1]))
{
printf("n-=-=-=-=-=-=-=-=-=-=-=-=-=-n");
printf(" Access Granted.n");
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-n");
}
else {
printf("n-=-=-=-=-=-=-=-=-=-=-=-=-=-n");
printf("nAccess Denied.n");
printf("n-=-=-=-=-=-=-=-=-=-=-=-=-=-n");
}

}
else { printf("Unauthorised User!!n"); exit(0); }
}

我需要帮助来检查下面的代码集是否以正确的方式编写,因为我不熟悉c++。

  1. fgets(第11行和第32行)
  2. strcpy_s(第12行)
  3. sprintf_s (line 34)

因为这行代码在我从另一个源获得它们之前有错误。然而,我修复了这些错误,但在运行时程序没有正常工作。程序实际上应该请求用户名和密码,并使用该用户名验证用户是否获得授权,并使用其密码验证用户所在的部门。但是,我只能在运行程序时输入用户名。它没有要求我输入密码。总的来说,是否有其他问题可能导致程序不能正常运行。

程序执行结果

程序不请求密码,因为它希望它作为这样的参数传递:'c:yourapp.exe yourpass'。如果你想让它请求密码,你应该稍微修改一下。

在main函数的if (check_authentication(argv[1]))行之前添加以下行。

char password[16];
printf("Password: ");
fgets(password, 16, stdin);

if (check_authentication(password))代替if (check_authentication(argv[1]))

并删除或注释掉下面的行:

if (argc < 2)
{
printf("Usage: %s <password>n", argv[0]); exit(0);
}

最后请不要忘记在每次fgets调用后删除换行符。从fgets()输入中删除尾随换行符

最新更新