不明白为什么我会出现段错误

Can't understand why I'm getting a segfault

本文关键字:段错误 错误 明白 为什么      更新时间:2023-10-16

我在堆栈上使用的内存很少,而且我没有递归,我所有的内存访问都在堆栈上。那么为什么我会得到一个段错误呢?

#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++

我看到了几个问题。

  1. 您没有检查fopen()是否成功。
  2. 您正在尝试读取 items[0].type ,它尚未初始化以指向任何有效内容。

您最好使用std::ifstreamstd::string而不是使用FILE*char*