不明白为什么我会出现段错误
Can't understand why I'm getting a segfault
我在堆栈上使用的内存很少,而且我没有递归,我所有的内存访问都在堆栈上。那么为什么我会得到一个段错误呢?
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[]){
FILE *file = fopen("test.cpp", "r");
struct item{
char *type;
int price;
bool wanted;
};
item items[100]; char *temp;
if (file)
cout << "works up to here" << endl;
fscanf(file,
"%s, %[for sale wanted], %d",
items[0].type,
temp,
&items[0].price);
}
它打印出来
works up to here
Segmentation fault (core dumped)
您正在传递指向未初始化fscanf
的指针。你需要做这样的事情:(如果您使用的是 C)
FILE* file = fopen(...);
char* str = malloc(N);
fscanf(file, "%s", str);
printf("Read %sn", str);
free(str);
fclose(file);
(如果您实际使用C++)
std::ifstream file(...);
std::string str;
file >> str;
std::cout << "Read " << str << std::endl;
scanf()
函数不会分配任何内存。从外观上看,您将未初始化的指针传递给函数需要足够大小的数组fscanf()
。
您很可能会使用类似的东西
items[0].type = new char[100];
char temp[20];
if (3 == fscanf("%100s, %[for sale wanted], %d",
items[0].type,
temp,
&items[0].price)) {
// deal with a read item
}
else {
// deal with an input error
}
(我对fscanf()
不够熟悉,无法对中间格式说明符充满信心)。
您是否检查过file
指针是否不为空?
这是来自 fopen 参考文档:
如果文件成功打开,该函数将返回指向一个 FILE 对象,可用于在将来标识流操作。
否则,将返回空指针。
正如凯文所提到的,这更像是C而不是C++
我看到了几个问题。
- 您没有检查
fopen()
是否成功。 - 您正在尝试读取
items[0].type
,它尚未初始化以指向任何有效内容。
您最好使用std::ifstream
和std::string
而不是使用FILE*
和char*
。
相关文章:
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 如何摆脱C ++中的分段错误错误?
- Clang 8 带有静态 constexpr 和数组的链接器错误 - 错误是什么以及如何解决它?
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 如何解决分段错误错误C++
- 作为参数模板的模板类:MSVC 错误 - 错误 C2977:模板参数过多 (C++98)
- 安卓工作室 |CPP 文件错误错误: 位图库中对"AndroidBitmap_unlockPixels"的未定义引用
- 卷曲给出分段错误错误
- 无法访问 Arduino 结构字段。错误"退出状态 1。xxxx 不命名类型"
- 错误错误 C2872:"布尔值":kinect.h 的不明确符号
- C++打印模板容器错误(错误:"运算符<<"的不明确重载)理解?
- 结构的分割错误错误
- 为什么此代码返回分段错误错误?
- 错误错误:无法编译内置功能
- 分段错误错误C++
- C++ 1Z 错误:错误:演绎指南中声明中的显式限定
- 使用对数据类型的向量的哈希表中的分段错误错误
- 为什么此代码会导致分段错误错误
- JNA结构字段值错误
- C++段故障错误