如何解决为什么scanf会引起无限的醇
我只是开始C而我不知道为什么会这样。当我执行该程序时,它仅在service_code
数组中存储了1个值。由于某些原因,scanf()
会将循环计数器i
保持为0。我找不到解决方案。 scanf()
使forloop无限运行。有人知道如何解决这个问题吗?
#include <stdio.h>
#include <string.h>
int main() {
char name [100];
char str [10];
int discount = 0 ;
int age;
char service_codes[4][6];
printf("Welcome to Nelson Lanka Hospital \n");
printf("Our Services : \n SV105 - Doctor Channeling \n SV156 - Pharmacy \n SV128 - Laboratory \n SV100 - OPD \n \n");
printf("Enter your Details \n Name : ");
scanf("%[^\n]",name);
printf(" Enter age : ");
scanf("%d",&age);
printf(" Enter the Sevice code for the service you need : ");
scanf("%s",str);
strcpy(service_codes[0],str);
for(int i = 1; i<4; i++){
char yn [2] = "y";
printf("Do you need any other sevices? (y/n) : ");
gets(yn);
if (strcmp(yn,"n")==0){
break;
}
printf(" Enter the Sevice code for the service you need : ");
scanf("%s",str);
strcpy(service_codes[i],str);
printf("%s \t %s \t %d \n",service_codes[i],str,i);
}
for (int x = 0; x<4; x++){
printf("%s \n",service_codes[x]);
}
}
解决方法
由于某种原因,scanf()会将循环计数器i保持为0。
您可能正在缓冲区溢出中,该缓冲区溢出正在更改堆栈中的变量(例如变量i
)。我在程序中至少看到两点可能发生缓冲区溢出:
-
scanf("%s",str);
:数组str
仅可容纳9个字符(另加1个结尾的空字符用作字符串终止符)。如果您输入的字符串长度超过9个字符(包括在按ENTER键时附加的换行符和回车符),则scanf
将破坏堆栈。 -
strcpy(service_codes[i],str);
:数组service_codes
中的每个元素都定义为每个都有6个字节(5个字符的空间加1个空终止符)。通过复制这样的字符串(其中str
可能比service_code
长),您将遇到缓冲区溢出。
C是一种强大的语言,它使您可以做任何事情,甚至可以自己动手射击。您必须对在代码中编写的每一行都保持谨慎!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。