问题描述:

I am trying to develop a simple 3d-model viewer, which should be able to read files line by line in the obj format. This seemed to be very simple, however when std::getline hits eof, the program exits with a segmentation fault.

Here, I've made the smallest amount of code which gives me a segfault (I use std::cin here, so that my program doesn't end immediately, but I actually get a chance to input some stuff into it, and manually enter an eof):

std::string line;

while(std::getline(std::cin, line))

{

std::cout<<line;

}

Another thing to notice is, that this code will only produce a segfault if the line containing eof is empty, otherwise, if eof is entered on a line containing anything else, the loop simply carries on.

Edit:

Now, I've reproduced this with the smallest code possible:

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;

}

Model.h

#ifndef MODEL_H_INCLUDED

#define MODEL_H_INCLUDED

namespace obj

{

class Model

{

public:

Model(const char* path);

};

}

#endif // MODEL_H_INCLUDED

Model.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;

}

}

}

网友答案:

The problem is that your code has two conflicting declarations of Model.

In Model.cpp you have

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

private:
    std::string name = ""; // Remove this line, and all works.
};

but in Model.h you have

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

You should have one definition of Model only, put that in Model.h and #include "Model.h" in Model.cpp

网友答案:

This looks like an error although the logic is hard to follow.

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;
    }
}

It's more logical with < not > since your vertices vector is initially size 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;
    }
}
相关阅读:
Top