繁体   English   中英

程序正确执行然后出现段错误

[英]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 ++运行时所需的内存中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM