从文件读取后出现分段故障(核心转储)

Segmentation Fault (Core Dumped) After reading from file

本文关键字:故障 核心 转储 分段 文件 读取      更新时间:2023-10-16

我正在尝试读取一个.txt文件,它看起来像这样。。。

Rhombus 118.5 112.4 69.9

然后,我尝试用参数或值118.5112.469.9初始化Shapes类的构造函数。然而,我得到了一个Segmentation Fault (Core Dumped)错误——我知道它来自我的代码中的哪一行。我只是不知道如何解决…

我的代码如下。。。

istream& inputpoints(istream &is, Shapes * & shape)
{
   string name;
   double x, y, z;
   if (is >> name) {
       if (is >> x >> y >> z) {
           *shape = Shapes(x, y, z); // Segementation fault (core dump) happening here
       }
   }
   return is;
}

我相信是线路*shape = Shapes(x, y, z)造成了所有这些问题。如果我不把*放在shape之前,那么我会得到一个Shapes不能分配给Shapes*的错误。

如果有人能在这里帮我,我将不胜感激。

感谢

几个问题。主要是将指向临时(堆栈)对象的指针分配给out参数。

为了更好的样式和可读性,请声明函数,使第二个参数是指向ppShapes的指针。

istream& inputpoints(istream &is, Shapes** ppShapes)
{

要解决主要问题,请更改此行:

*shape = Shapes(x, y, z); // Segementation fault (core dump) happening here

成为这样:

*ppShapes = new Shapes(x, y, z);

调用输入点如下:

Shapes* pShapes = NULL;
istream = inputpoints(istream, &pShapes);