使用fgets将数据读入未初始化的char指针变量时,在第二次读取时崩溃 [英] Reading data into an uninitialized char pointer variable using fgets crashes at the second read

查看:74
本文介绍了使用fgets将数据读入未初始化的char指针变量时,在第二次读取时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们无法使用fgets将数据读取到未初始化的char指针中.关于stackoverflow的这一点,有很多问题.所有答案都表明您无法将数据加载到未初始化的指针变量中.

I am aware that we cannot read data into an uninitialized char pointer using fgets. There are quite a few questions relating to this very point here on stackoverflow. All the answers point to the fact that you can't load data into an uninitialized pointer variable.

第一个代码片段中显示的程序能够使用fgets填充第一个未初始化的char指针(* str2),但是在尝试将数据读取到第二个未初始化的char指针(* str3)时崩溃.

The program shown in the first code snippet is able to populate the first uninitialized char pointer (*str2) using fgets but, crashes while trying to read data into the second uninitialized char pointer (*str3).

我可以使用传统方法使其工作,例如在填充之前预先为指针分配内存(如下面的第二个代码片段所示).我的问题是为什么它对第一个变量有效,但对第二个变量无效?

I can get it to work using the traditional methods like allocating memory to the pointer up-front (as shown in the second code snippet below) before populating. My question is why does it work for the first variable but not for the second?

问题代码

#include <stdio.h>

int main()
{
    char str1[100], *str2, *str3;
    // Prints fine

    printf("First String: ");
    fgets(str1, 20, stdin);
    printf("%s", str1);

    // Prints fine      
    printf("Second String: ");
    fgets(str2, 20, stdin);
    printf("%s", str2);

    // Program crashes on this input
    printf("Third String: ");
    fgets(str3, 20, stdin);
    printf("%s", str3);

    return 0;

}

工作代码

#include <stdio.h>

int main()
{
    char str1[100], str2[20], str3[20];
    printf("First String: ");
    fgets(str1, 20, stdin);
    printf("%s", str1);

    printf("Second String: ");
    fgets(str2, 20, stdin);
    printf("%s", str2);

    printf("Third String: ");
    fgets(str3, 20, stdin);
    printf("%s", str3);

    return 0;

}

推荐答案

在您的情况下

// Prints fine      
printf("Second String: ");
fgets(str2, 20, stdin);
printf("%s", str2);

包含对未初始化指针的写入,该指针包含不确定的值,这意味着它将调用未定义行为.

contains the write to uninitialized pointer, which contains indeterminate value, which means, it invokes undefined behavior.

一旦您的程序具有UB,就无法保证.拥有UB的副作用之一是表现为正常(正常)工作",并且也不保证崩溃"或分段错误.就是这样,未定义.

Once your program has UB, nothing is guaranteed. One of the side-effects of having UB is to appear as "working (ab)normally", and a "crash" or segmentation fault is not guaranteed, either. It's just that, undefined.

故事的寓意:不要试图用从包含未定义行为的程序获得的输出来推理.

Moral of the story: Do not try to reason with the output obtained from a program containing undefined behavior.

这篇关于使用fgets将数据读入未初始化的char指针变量时,在第二次读取时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆