c - c语言程序中的分段错误(核心转储)?
问题描述
我是一名学生,我正在学习 c(ANSI c -> 第五版编程)并面临以下错误:
我正在用 typedef 实现一个程序
在下面的 c 程序中给出一个错误:
main.c:8:6: warning: ‘gets’ is deprecated [-Wdeprecated-declarations]
/usr/include/stdio.h:638:14: note: declared here
main.c:(.text+0x1f): warning: the `gets' function is dangerous and should not be used.
enter name:cara
Segmentation fault (core dumped)
程序:
#include <stdio.h>
char * read(void); //here I m writing prototype but I don't know what is the prototype and why here write the prototype?
char * read(void)
{
char * name;
printf("enter name:");
gets(name); //get string input using gets(..) function
return name;
}
void main()
{
char * name;
name = read();
printf("welcome,%s\n",name);
}
上面的程序很复杂,这就是我在下面的程序中使用 typedef 的原因:
这个下面的程序为什么连续运行?
#include <stdio.h>
typedef char * string;
string read(void);
string read(void)
{
string name;
printf("enter name:");
gets(name);
return name;
}
void main()
{
string name;
name = read();
printf("welcome,%s\n",name);
}
我做错了什么?
解决方案
这有几个问题。当你这样做时char * name
,你定义name
为一个 char 指针,但你实际上并没有为要存储的字符串分配任何空间。因此,当您尝试将值写入该字符串时,您将值写入可能不可写或可能包含无法覆盖的关键数据的随机位置。相反,尝试将 name 声明为char name[256];
为其分配足够的空间。另外,不要使用gets
,因为它会导致非常非常讨厌的事情。相反,用于fgets
读取输入,并提供与您分配的数据量相等的字符数上限。因此,如果您将 name 声明为char name[256];
,请使用 fgets 调用fgets(name, 256, stdin);
推荐阅读
- pandas - 如何将包含元组列表的字典中的字典转换为熊猫数据框
- azure - 如何将 Azure DevOps 的变量替换为 PowerShell 的变量?
- ios - 在 Objective-C 中取消定义重复的接口
- python - 如何从每个键的键列表中初始化 python 中的字典以具有相同的初始值?
- elasticsearch - 使用 elasicsearch 按具有 id 的参考列对行进行排序
- c# - Powershell 命令返回空字符串
- reactjs - React-player:开始视频时在移动设备上禁用全屏
- java - resolveActivity(getPackageManager()) != null 返回 null
- excel - 应用自动过滤器来分隔同一工作表上的数据“块”
- javascript - 如何循环播放 svg 文本动画?