I have a problem trying to load a 3d object from a wavefront file and saving it into a structure that I predefined. I get a segmentation fault error, I`m assuming that I have gone wrong with my pointers somewhere. Here are the sructures:
struct vertex
{
float x,y,z;
};
// the idea is to split each object into groups in order to animate
// them seperately
struct group
{
float xpos, ypos, zpos;
float xrot, yrot, zrot;
int numVertices;
int numFaces;
//all verteces
vertex vertices[MAX_NUM];
//faces-- a face is made up of one vertex from each of these arrays
vertex vertexOne[MAX_NUM];
vertex vertexTwo[MAX_NUM];
vertex vertexThree[MAX_NUM];
};
struct object
{
float xpos, ypos, zpos;
float xrot, yrot, zrot;
int numGroups;
group * groups[MAX_NUM];
};
This is the function that should load the object:
object * loadObject(char * path)
{
object * obj;
obj = new object;
char str[1];
obj->numGroups = 0;
FILE * file = fopen(path, "r");
while(fscanf(file, "%s", str) != EOF)
{
if(str[0] == 'o')
{
obj->numGroups++;
obj->groups[obj->numGroups-1] = new group;
obj->groups[obj->numGroups-1]->numVertices = 0;
obj->groups[obj->numGroups-1]->numFaces = 0;
}
else if(str[0] == 'v' && str[1] == ' ')
{
obj->groups[obj->numGroups-1]->numVertices++;
sscanf(str, "v %f %f %f",
&(obj->groups[obj->numGroups-1]->vertices[obj->groups[obj->numGroups-1]->numVertices-1].x),
&(obj->groups[obj->numGroups-1]->vertices[obj->groups[obj->numGroups-1]->numVertices-1].y),
&(obj->groups[obj->numGroups-1]->vertices[obj->groups[obj->numGroups-1]->numVertices-1].z));
}
else if(str[0] == 'f')
{
int one, two, three;
obj->groups[obj->numGroups-1]->numFaces++;
sscanf(str, "f %i/%*i/%*i %i/%*i/%*i %i/%*i/%*i", &one, &two, &three);
obj->groups[obj->numGroups-1]->vertexOne[obj->groups[obj->numGroups-1]->numFaces-1] = obj->groups[obj->numGroups-1]->vertices[one-1];
obj->groups[obj->numGroups-1]->vertexTwo[obj->groups[obj->numGroups-1]->numFaces-1] = obj->groups[obj->numGroups-1]->vertices[two-1];
obj->groups[obj->numGroups-1]->vertexThree[obj->groups[obj->numGroups-1]->numFaces-1] = obj->groups[obj->numGroups-1]->vertices[three-1];
}
}
fclose(file);
return obj;
}
I have tried for quite a while to find the problem but i get no information on the error at all. I know the way I`m assigning the vertices and faces is a bit tedious, any suggesstions for neater code are very welcome. Please tell me if any additional information is needed, thank you very much in advance.
First you do
Then in some cases you do
without increasing
obj->numGroups, meaning you access the array way out of bounds. You also don’t check if the array entry been allocated or not.Another problem is that
stris only one character, and yourfscanfscans for a string which will put at least two character into the string: The actual character you want and then the string terminator character. You also accessstr[1]later in the loop, which is out of bounds. All of this is undefined behaviour and can lead to crashes.