首页 > 解决方案 > 为什么scanf会导致无限的forool

问题描述

我刚开始 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]);
}

}

标签: cloopsfor-loopscanf

解决方案


由于某种原因,scanf() 将循环计数器 i 保持为 0。

您可能有一个缓冲区溢出,它正在改变堆栈中的变量(例如 variable i)。我在您的程序中至少看到两个可能发生缓冲区溢出的点:

  • scanf("%s", str);:数组str只有 9 个字符的空间(加上 1 个用作字符串终止符的结束空字符)。如果您输入的字符串长度超过 9 个字符(包括按 ENTER 时附加的换行符和回车符),scanf则会损坏堆栈。

  • strcpy(service_codes[i], str);:数组中的每个元素service_codes被定义为每个元素有 6 个字节(5 个字符的空间加上 1 个结束空终止符)。通过复制这样的字符串,其中str可能比 长service_code,您将遇到缓冲区溢出。

C 是一种强大的语言,它可以让你做任何事情,甚至是在你自己的脚下射击。您在代码中编写的每一行都必须小心!


推荐阅读