문제

this is a c++ question.

I'm working on an OpenGL project. wrote a simple OBJ loader. I have a class called Mesh. By getting an object pointer called monkey

Mesh* monkey;

and calling function:

load_obj("Monkey.obj", monkey);

I want to read from file and put it in monkey vertices. but when running it gives me unhandled exception:read violation when want to pushback to vector at:

mesh->vertices.push_back(v);

I tested a local vector dummy but it successfully pushedback. I don't know why it can't push to the object pointers vector?

here is the mesh header

include[...]

using namespace std;

class Mesh {
private:
  GLuint vbo_vertices, vbo_normals, ibo_elements;
public:
  vector <glm::vec4> vertices;
  vector <glm::vec3> normals;
  vector <GLushort> elements;
  glm::mat4 object2world;

  Mesh() : vertices(1), normals(1), elements(3), object2world(glm::mat4(1)) {}
  ~Mesh(void){} ;
  void Mesh::draw(void) ;

};

and this is the obj-loader.cpp relative part

void load_obj(const char* filename, Mesh* mesh) {
  ifstream in(filename, ios::in);
  if (!in) { cerr << "Cannot open " << filename << endl; exit(1); }
  vector<int> nb_seen;
  vector<glm::vec4> dummy;
  string line;
  while (getline(in, line)) {
    if (line.substr(0,2) == "v ") {
      istringstream s(line.substr(2));
      glm::vec4 v; s >> v.x; s >> v.y; s >> v.z; v.w = 1.0;
      dummy.push_back(v);
      mesh->vertices.push_back(v);
    } 

any help would be appreciated! your confused friend!

도움이 되었습니까?

해결책 2

From the code fragments you have posted, it appears that you haven't actually allocated the mesh object. Declaring the pointer like this:

Mesh* monkey;

doesn't initialise the pointer or allocate any memory, so its value is undefined. That's why the loading code is crashing. Because the mesh pointer is invalid, and pointing to some garbage memory.

It should be something more like:

Mesh* monkey = new Mesh();

Then at least you will have a valid pointer which you can then legitimately refer to in the loader code.

다른 팁

You will have to allocate memory for Mesh

before calling

load_obj("Monkey.obj", monkey);

mesh is an uninitialized pointer on which you are using mesh->vertices. You got undefined behavior at this point already. You probably need have mesh point to an object.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top