使用fgets将数据读入未初始化的char指针变量时,在第二次读取时崩溃

编程入门 行业动态 更新时间:2024-10-16 22:13:09
本文介绍了使用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指针变量时,在第二次读取时崩溃

本文发布于:2023-07-28 02:30:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226470.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   指针   变量   数据   fgets

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!