使用getline读取文件/输入时出现分段错误

Segmentation fault while reading file/input with getline

本文关键字:分段 错误 输入 getline 读取 文件 使用      更新时间:2023-10-16

我正在尝试开发一个简单的三维模型查看器,它应该能够逐行读取obj格式的文件。这看起来很简单,但是当std::getline碰到eof时,程序会以分段错误退出。

在这里,我制作了最少量的代码,这给了我一个segfault(我在这里使用std::cin,这样我的程序就不会立即结束,但我实际上有机会向其中输入一些东西,并手动输入eof):

std::string line;
while(std::getline(std::cin, line))
    {
        std::cout<<line;
    }

另一件需要注意的事情是,只有当包含eof的行为空时,此代码才会产生segfault,否则,如果在包含其他内容的行上输入eof,则循环只会继续

编辑:现在,我用尽可能小的代码复制了这个:

main.cpp

#include <iostream>
#include "Model.h"
int main(int argc, char* argv[])
{
    std::string path = "/home/thor/Skrivebord/3d_files/Exported.obj";
    obj::Model(path.c_str());
    return 0;
}

型号.h

#ifndef MODEL_H_INCLUDED
#define MODEL_H_INCLUDED
namespace obj
{
    class Model
    {
    public:
        Model(const char* path);
    };
}
#endif // MODEL_H_INCLUDED

型号.cpp

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
namespace obj
{
    class Model
    {
    public:
        Model(const char* path);
    private:
        std::string name = ""; // Remove this line, and all works.
    };
    Model::Model(const char* path)
    {
        std::string line;
        while(std::getline(std::cin, line))
        {
            std::cout << line;
        }
    }
}

问题是您的代码有两个冲突的Model声明。

在Model.cpp中,您有

class Model
{
public:
    Model(const char* path);
private:
    std::string name = ""; // Remove this line, and all works.
};

但在Model.h中,您有

class Model
{
public:
    Model(const char* path);
};

您应该只有一个Model的定义,将其放在Model.h中,将#include "Model.h"放在Model.cpp 中

尽管逻辑很难理解,但这看起来像是一个错误。

void Face::AddVertex(float x, float y, float z)
{
    if (vCnt > 3)
    {
        vertices[vCnt].SetPos(x, y, z);
        ++vCnt;
    }
    else
    {
        vertices.push_back(Vertex(x, y, z));
        ++vCnt;
    }
}

<而不是>更符合逻辑,因为vertices矢量最初的大小是3

void Face::AddVertex(float x, float y, float z)
{
    if (vCnt < 3)
    {
        vertices[vCnt].SetPos(x, y, z);
        ++vCnt;
    }
    else
    {
        vertices.push_back(Vertex(x, y, z));
        ++vCnt;
    }
}