程序正确执行,然后出现段错误
Program executes correctly then segfaults
在程序结束时,我的数组正确打印出来,然后程序出现段错误。为什么?
#include <iostream>
#include <stdio.h>
#include <iomanip>
#include <string.h>
using namespace std;
int main(int argc, char *argv[]) {
FILE *file = fopen(argv[1], "r");
struct item{
char type[9];
int price;
bool wanted;
};
item items[20]; char temp[8];
for (char i = 0; i < 100; i++)
{
if (fscanf(file,
"%[^,], %[^,], %d",
items[i].type,
temp,
&items[i].price) != 3)
break;
else if (!strcmp(temp, "for sale"))
items[i].wanted = false;
else if (!strcmp(temp, "wanted"))
items[i].wanted = true;
else
cout << "aaaagghghghghhhh!!!" << endl;
}
for (char i = 0; i < 100; i++)
{
cout << items[i].type << endl;
cout << items[i].price << endl;
cout << items[i].wanted << endl;
}
}
你的数组声明只有 20 个空格,但你的循环是 100 个。也许将您的数组更改为具有 100 个空格。
用
item items[100];
溢出数组会导致未定义的行为。在程序堆栈展开等过程中,您的代码可能会写入C++运行时所需的内存中。
相关文章:
- 编写代码时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++段故障错误