Skip to main content
gamedev.net
🔒 Locked

Dynamic array of structures causing errors at runtime

Started by Feblex 1 reply 850+ views
Original Post
Feblex
Feblex
I doubt this is the proper methodology for doing it, so if someone could point a better way to do this, I''d much appreciate it. I have a text file containing geometry data in this form:

 2
-2.00 2.00 -5.00 2 0.00 0.00
-2.00 0.00 -5.00 2 0.00 1.00
2.00 0.00 -5.00 2 1.00 1.00

2.00 2.00 -5.00 2 1.00 1.00
2.00 0.00 -5.00 2 1.00 0.00
-2.00 2.00 -5.00 2 0.00 1.00

The first line indicates an integer declaring the number of triangles within the file. During file-loading, I use the following bit to read that first line in:
fscanf(Worldat, "%d", &numtri);
numvert = (numtri * 3)+1;
In this way, I turn numtri, number of triangles, into the number of vertices, numvert. Now, I have a structure called Vector declared in a header file:
 typedef struct{
	float x;
	float y;
	float z;
} Vector;

extern Vector* Geometry;
Back in the file-loading code, I try to declare a dynamic array of this structure to hold the information in the file:
Vector *Geometry;
Geometry = new Vector[numvert];


for (int i=0; i<numvert; i++) {
fscanf(Worldat, "%f %f %f %d %f %f", &Geometry[i].x, &Geometry[i].y, &Geometry[i].z);			
}
Everything compiles beautifully. However, at run-time, I get one of those nice "EngineTest has caused an error EngineTest.exe" boxes. On Debug, tells me there''s an "Unhandled Exception in EngineTest.exe: 0X0000005: Access Violation" which then takes me to a place in something called fassign in what I can only assume is a .c file belonging to the compiler. Why is it doing this? I''ve never done anything like this before, and everytime I''ve come across an unhandled exception like this, it''s been a really simple mistake on my part. I''d love to learn from it, but everything I''ve read tells me I''m doing this right. Much thanks and appreciation in advance to whomever can help me out!
Feblex
Feblex
*bump*
Zahlman
Zahlman
My suspicion is that you need to read the other fields into temporary variables as well. You have 6 %-thingies in your scanf, so the internal varargs handling is expecting 6 more parameters to be passed, but you only supply 3. Varargs are really low-level, nasty stuff lacking in error checking, so my guess is that it''s grabbing random memory pointers beyond the end of the stack and trying to assign the rest of the file data through them, to random locations in memory - and bang you''re dead.


typedef union {
int foo;
float bar;
} junk;

junk j;

for (int i=0; i<numvert; i++) {
fscanf(Worldat, "%f %f %f %d %f %f", &Geometry[i].x, &Geometry[i].y, &Geometry[i].z, &junk, &junk, &junk);
}


(And I assume you have good reason for using C in the first place.)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.