Hi! I've a problem, I've done a class called Model that can load 3D models for an OpenGL application. It works just as it should and have member functions to display the models. It can look like this:
1 2 3 4
#include "model.h"
Model m1("model.3ds");
m1.drawModel();
Loading the models everytime I want to use one is ofcourse unacceptable so I've done a class to store the models and return pointers to them whenever I need them.
#include "model_list.h"
Model_List::Model_List()
{
}
// This functions returns a pointer to a model if it is in the list, otherwise it appends the model to the list and retuns a pointer to it.
Model * Model_List::getModel(constchar * modelname)
{
// Check for the existence of the model by name in the model_list.
for(int i = 0; i < model_list.size(); i++)
{
if(model_list[i].name == modelname)
{
return &model_list[i].model;
}
}
// If nothing was returned in the for-loop we append a model-object to model-list and return a pointer to it.
model_object temp;
temp.name = modelname;
temp.model = Model(modelname);
model_list.push_back(temp);
return &temp.model;
}
Then main.cpp:
1 2 3
Model_List ml;
Model * m1 = ml.getModel("model.3ds");
m1->drawModel();
I hope the comments are clear, getModel goes through a vector with structs containing the name of the model and the actual model. If a model is in the vector a pointer to it is returned, if it isn't we load the 3D model and return a pointer to it.
It goes well to call that function getModel() however when I call m1->drawModel() I get a segmentation fault. After following the debugger the segmentation fault occurs in one of the Model-class' library files to load 3D models. This is what I think is so strange because the debugger shows that it reaches the member-functions of Model so appearently the pointer m1 is pointing to a Model.
I don't know if it can help if I go into detail how Model works because the problem obviously seems to be somewhere in the files I've posted as everything else works. Please also say if everything looks fine and should work as I've described.
I would really aprichiate some help, or thought no matter how big or small because I'm completly stuck :)
In Model_List::getModel(), you are allocating temp on the stack and then returning a pointer to the stack instance. But the stack instance goes away as soon as the function returns, so you are essentially returning a dangling pointer. To fix that problem, you need to return &model_list.back().
However, you should understand that if the vector you are using ever needs to be resized, it will _copy_ (via copy constructor) all of the elements of the original vector, and this can be _very_ expensive in your application.
I would highly recommend either storing pointers in the vector or using a different STL container (such as list, which will not have that nasty side effect).