鱼C论坛

 找回密码
 立即注册
查看: 110|回复: 4

[已解决]程序异常中断

[复制链接]
发表于 7 天前 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <stdio.h>
int main(){
    char str1[30] = {0};
    char str2[30] = {0};
    char str3[30] = {0};

    //gets() 用法
    printf("Input a string: ");
    gets(str1);

    //scanf() 用法
    printf("Input a string: ");
    scanf_s("%s", str2);
     scanf_s("%s", str3);
   
    printf("\nstr1: %s\n", str1);
    printf("str2: %s\n", str2);
    printf("str3: %s\n", str3);
        while(1);
    return 0;
}
最佳答案
7 天前
scanf_s("%s", str2);
scanf_s("%s", str3);
        改为:
scanf_s("%s" , str2 , 30);
scanf_s("%s" , str3 , 30);
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 7 天前 | 显示全部楼层
你好,根据你的代码,程序会在`gets()`函数调用时出现异常中断。这个问题主要涉及到几个方面:

1. **字符串数组初始化问题**:
   你将字符串定义为`char`类型数组,并在初始化时长度为1(`{0}`),所以只能存储一个字符。另外,初始化方式有问题。
   
2. **使用`gets()`函数的问题**:
   `gets()`是比较危险的函数,它不对输入的长度进行检查,可能会导致缓冲区溢出。这也是在C11标准中被废弃的原因。建议使用`fgets()`代替。

3. **使用`scanf_s()`的方式不正确**:
   `scanf_s()`是微软引入的安全版本,需要额外的参数来指定缓冲区的大小。你需要在每次读取字符串时指明缓冲区长度。

可以按照以下修改方式重新编写代码:
#include <stdio.h>

int main() {
    char str1[100] = {0};  // 增大数组大小
    char str2[100] = {0};
    char str3[100] = {0};
    
    // 使用 fgets 代替 gets
    printf("Input a string: ");
    fgets(str1, sizeof(str1), stdin);
    
    //使用 scanf_s,正确方式
    printf("Input a string: ");
    scanf_s("%99s", str2, (unsigned)_countof(str2));

    printf("Input another string: ");
    scanf_s("%99s", str3, (unsigned)_countof(str3));
    
    printf("\nstr1: %s\n", str1);
    printf("str2: %s\n", str2);
    printf("str3: %s\n", str3);

    while(1);
    return 0;
}

关键修改点:

1. 增大了字符数组的大小,防止溢出。
2. 使用`fgets()`代替`gets()`,可以防止缓冲区溢出。
3. `scanf_s()`的使用需要额外参数来指定缓冲区长度。

以上修改将会避免程序异常中断问题,更加安全稳定。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 7 天前 | 显示全部楼层    本楼为最佳答案   
scanf_s("%s", str2);
scanf_s("%s", str3);
        改为:
scanf_s("%s" , str2 , 30);
scanf_s("%s" , str3 , 30);
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 7 天前 | 显示全部楼层
scanf_s("%s", str2);
scanf_s("%s", str3);
        改为:
scanf("%s", str2);
scanf("%s", str3);
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 6 天前 | 显示全部楼层
把 scanf_s 改成 scanf
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 15:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表