我目前正在学习C,并且正在从事一项任务,以改善可能导致程序崩溃的某些C代码。
这里是代码:
int main()
{
// Define buffers to store username and password
char username[16];
char password[16];
// Read username and password from user input
printf("Enter your name: ");
scanf("%s", username);
printf("Enter your password: ");
scanf("%s", password);
printf("[SHOUTING OUT LOUD] Hello, %s!\n", username);
return 0;
}
如何确定输入的字符数不超过15个字符?否则,程序可能会意外打印出密码或覆盖堆栈上的返回地址。我已经考虑过将变量放在堆上,但是一开始我不知道输入要多长时间。所以我不知道我要分配多少空间。
有人可以帮我吗?谢谢:)
为bufferlength - 1
转换说明符使用长度为%s
的长度说明符:
printf("Enter your name: ");
if (scanf("%15s", username)) != 1)
{
fputs("Error at input - username!", stderr);
exit(1);
}
printf("Enter your password: ");
if (scanf("%15s", password)) != 1)
{
fputs("Error at input - password!", stderr);
exit(1);
}
或改用fgets()
:
printf("Enter your name: ");
if (fgets(username, sizeof(username), stdin) == NULL)
{
fputs("Error at input - username!", stderr);
exit(1);
}
size_t len = sizeof(username);
for (size_t i = 0; i < len; i++)
{
if ( username[i] == '\n' )
{
username[i] = '\0'; // replace newline with NUL.
break;
}
if ( i == len - 1 )
{
getchar(); // catch left newline from stdin.
}
}
printf("Enter your password: ");
if (fgets(password, sizeof(password, stdin) == NULL)
{
fputs("Error at input - password!", stderr);
exit(1);
}
password[strcspn(password, "\n")] = '\0'; // replace newline with NUL.