[英]C-Linux-Stack smashing detected! for validating input with while loop
int test()
{
char choice[2];
int score = 0;
puts("\nPlease ONLY answer with Y or N.\nQ1. (Y or N) ");
scanf("%s", choice);
while (strcmp(choice, "Y") && strcmp(choice, "y") && strcmp(choice, "n") && strcmp(choice, "N"))
{
printf("\nEnter valid Input(Y or N) : ");
scanf("%s", choice);
}
if (!strcmp(choice, "Y") || !strcmp(choice, "y"))
score += 30;
puts("Q2. (Y or N) ");
scanf("%s", choice);
while (strcmp(choice, "Y") && strcmp(choice, "y") && strcmp(choice, "n") && strcmp(choice, "N"))
{
printf("\nEnter valid Input(Y or N) : ");
scanf("%s", choice);
}
if (!strcmp(choice, "Y") || !strcmp(choice, "y"))
score += 20;
puts("Q3. (Y or N) ");
scanf("%s", choice);
if (!strcmp(choice, "Y") || !strcmp(choice, "y"))
score += 20;
return score;
}
当我调用它时,如果用户只输入 y Y n N,则代码可以正常工作,但如果用户输入任何其他内容,甚至一次,在问题结束时,我
stack smashing error detected
,我该如何解决这个问题?
char choice[2]; scanf("%s", choice);
是一场等待发生的灾难。
输入缓冲区choice
只有 2 个字符,因此字符串只能容纳 1 个字符。 但是允许scanf
在该位置放置任意数量的字符。 因此,如果用户在按 Enter 之前输入了超过 1 个字符,这些额外的字符将存储在 memory 中,而不是存储它们。 因此它会覆盖属于其他数据的 memory,在这种情况下是您的堆栈帧。 这是由堆栈粉碎检测器检测到的。 一般来说,你可以覆盖任何东西,这总是很糟糕。
始终确保您保持在变量的范围内。 因此,使用格式字符串%1s
强制scanf
忽略除第一个字符以外的所有字符。
#include <stdio.h>
#include <string.h>
int main()
{
char choice;
int score = 0;
puts("Q1. (Y or N) ");
do
{
printf("\nEnter valid Input(Y or N) : ");
scanf(" %c",&choice);
}while (choice!='y'&&choice!='Y'&&choice!='n'&&choice!='N');
if(choice=='y'||choice=='Y')
{
score += 30;
}
puts("Q2. (Y or N) ");
do
{
printf("\nEnter valid Input(Y or N) : ");
scanf(" %c",&choice);
}while (choice!='y'&&choice!='Y'&&choice!='n'&&choice!='N');
if(choice=='y'||choice=='Y')
{
score += 20;
}
puts("Q3. (Y or N) ");
do
{
printf("\nEnter valid Input(Y or N) : ");
scanf(" %c",&choice);
}while (choice!='y'&&choice!='Y'&&choice!='n'&&choice!='N');
if(choice=='y'||choice=='Y')
{
score += 20;
}
printf("\n%d\n",score);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.