gpt4 book ai didi

c - 忽略 fscanf 的返回值和段错误

转载 作者:行者123 更新时间:2023-11-30 18:30:29 30 4
gpt4 key购买 nike

我想知道如何解决我的 C 代码上的核心转储问题

当我使用以下命令编译它时:g++ -g MatSim.cpp -o MatSim -lstdc++ -O3,我收到三个警告,这是一个(其他两个类似,仅通过字符串变量名):

MatSim.cpp: In function ‘int main()’:
MatSim.cpp:200037:27: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
fscanf(TM,"%255s",string2);

我的代码的主要方面以及编译器报告的相关部分:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int to_int(char string[256])
{
if( strcmp(string,"0") == 0 )
{
return 0;
}

...

else if( strcmp(string,"50000") == 0 )
{
return 50000;
}
return -1;
}

int main()
{
int a,b,div,value,k,i,j,tm,ler;
char string[256];
char string1[256];
char string2[256];

FILE *TM;
TM = fopen("TM","r");
if( (TM = fopen("TM","r")) == NULL)
{
printf("Can't open %s\n","TM");
exit(1);
}
fscanf(TM,"%255s",string2);
tm = to_int(string2);
fclose(TM);

...

}

我已尝试过 here 中报告的建议我试图理解 here 中发布的内容。但是,我在我的代码中没有看到它的应用。

最后,当我运行exe文件时,它返回:

Segmentation fault (core dumped)`.

最佳答案

在您的代码中,您fopen()该文件两次。只需摆脱

 TM = fopen("TM","r");

if 语句之前。

也就是说,您应该检查 fscanf() 的值以确保成功。否则,您最终将读取一个未初始化的数组 string2,它不是以 null 结尾的,进而调用 undefined behaviour .

请注意,几乎所有与字符串相关的函数都需要一个以 null 结尾的字符数组。如果你的数组不是以 null 结尾的,就会有 UB。另外,初始化自动局部变量是一个很好的做法,以避免在代码的后面部分中可能出现 UB。

关于c - 忽略 fscanf 的返回值和段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30873239/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com