When trying to read a file in a second time, the fopens function just crash my program returning no errors. And the weird thing is that the same function was working moments ago, and then is crashing at the same point after debugging
(The location of the files has not been changed)
(When i change the order of the files been readed is still the same, can read the first time, but the second time just crash)
vector<triangle> loadObj(const char* sfileName){
FILE* f = new FILE;
f = fopen(sfileName,"r");
if(f==nullptr){
fclose(f);
return {};
}
//Cache
vector<vec3d> ve;
vec3d v;
vector<triangle> cache;
char line[100];
while (fgets(line, sizeof(line), f)) {
strstream s;
s << line;
char junk;
if(line[0]=='v'){
s >> junk >> v.x >> v.y >> v.z;
ve.push_back(v);
}
else if(line[0]=='f'){
int p1,p2,p3;
s >> junk >> p1 >> p2 >> p3;
triangle t;
t.vertexs[0] = ve[p1-1];
t.vertexs[1] = ve[p2-1];
t.vertexs[2] = ve[p3-1];
cache.push_back(t);
}
}
fclose(f);
return cache;
}
Use function:
mesh* loadMesh(const char* file){
mesh* cubo = (mesh*) malloc(sizeof(mesh));
if (cubo == NULL){
return NULL;
}
cubo->tris = {};
cubo->tris = loadObj(file);
return cubo;
}
>Solution :
Your mesh class is clearly defined as something like:
struct mesh{
vector<triangle> tris;
}
Aside from C-style structs with no C++ features in use (structs essentially 100% compatible with C), malloc is inappropriate for safely allocating classes in C++; it won’t actually construct tris, it’ll just leave whatever random bytes were left in the heap as if they were already a validly constructed vector<triangle>, and the odds of that being correct are near zero.
Attempting to assign to cubo->tris with cubo->tris = {}; then tries to free the existing contents of said vector, which does terrible, random, and undefined things. placement new could be used to make this work. But don’t do that, because now you need to manually destruct the contents, and you’re not deriving any benefit either way. Using C allocators for C++-classes is a bad idea, don’t do it.
Short answer: If you’re using C++ features, use C++ allocators like new/delete (or better, std::make_unique/std::make_shared), not malloc/free. In this case, there’s no reason I can determine for dynamic allocation, so it’s possible the correct solution is to just return by value instead:
mesh loadMesh(const char* file){
return {loadObj(file)}; // Or return mesh(loadObj(file)); or whatever makes
// sense for the actual definition of mesh
}