首页 > 解决方案 > 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);
}

我做错了什么?

标签: ctypedefc-strings

解决方案


这有几个问题。当你这样做时char * name,你定义name为一个 char 指针,但你实际上并没有为要存储的字符串分配任何空间。因此,当您尝试将值写入该字符串时,您将值写入可能不可写或可能包含无法覆盖的关键数据的随机位置。相反,尝试将 name 声明为char name[256];为其分配足够的空间。另外,不要使用gets,因为它会导致非常非常讨厌的事情。相反,用于fgets读取输入,并提供与您分配的数据量相等的字符数上限。因此,如果您将 name 声明为char name[256];,请使用 fgets 调用fgets(name, 256, stdin);


推荐阅读