C linux中的分段错误
当我编译代码并运行它时,它会显示C linux中的分段错误,c,segmentation-fault,C,Segmentation Fault,当我编译代码并运行它时,它会显示分段错误 这是我的密码: #include <stdio.h> #include <string.h> #include <time.h> #include <stdlib.h> int main() { int i; char weather_value; char weather_incoming[2000]; FILE *in; in=fopen("home/pi/w
分段错误
这是我的密码:
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int i;
char weather_value;
char weather_incoming[2000];
FILE *in;
in=fopen("home/pi/weather_project/weather_incoming.txt","r");
for(i=0;i<2000;i++)
{
fscanf(in,"%c",&weather_incoming[i]);
}
char* tagStartBegin = strstr(weather_incoming,"<pty");
char* tagStartEnd = strstr(tagStartBegin,">");
char* value = tagStartEnd+1;
char* tagEndBegin = strstr(tagStartEnd,"</pty>");
*tagEndBegin = '\0';
weather_value=*value;
printf("%c",weather_value);
fclose(in);
}
#包括
#包括
#包括
#包括
int main()
{
int i;
焦耳值;
char weather_传入[2000];
文件*in;
in=fopen(“home/pi/weather_project/weather_incoming.txt”,“r”);
对于(i=0;i而言,给出的代码存在几个问题:
您不检查fopen是否成功。如果您试图打开的文件不存在,该怎么办
循环盲目读取2000fscanf
调用读取字符。如果文件包含少于2000个字符怎么办
您将一个非NUL结尾的字符串传递给strstr
,调用未定义的行为
您不检查strstr是否成功
如果使用C89,则需要对main
使用return
语句
解决方案:
检查fopen
的返回值。如果返回值为NULL
,则打开失败。如果是这种情况,则应采取必要的操作
不要盲目地重复2000次,而是一直读到fscanf
失败(当fscanf
返回EOF
时会发生这种情况)或当缓冲区大小达到最大值时。请注意,有更好的读取方法,而不是逐个字符读取
您应该在循环后NUL终止数组。请注意,您需要为此预留一个额外的空间
检查strstr
的返回值。如果该值为NULL
,则表明strstr
未能在草堆中找到指针。如果是这种情况,则应采取必要的措施
在main
的末尾添加return EXIT\u SUCCESS;
。main
的标准形式之一是int main(void)
,而不是int main()
您应该使用调试器(在Linux上,存在gdb)。代码有很多问题。
中的文件句柄将是错误的,您正在尝试从中读取。您确定home
而不是/home
?逐个字符读取文件看起来很奇怪fscanf()
。我敢打赌你的bug与此有关。改用fread()
,在一个read语句中读取整个文件。我想这会奏效。这就是问题所在thx:)始终检查函数的返回值,例如fopen
。我还想在main()
中添加一个关于缺少返回值的要点。。。