First I looked at your code, and decided that it would probably crash as you described because there is NO error checking at all inside the code.
Well I ran your code, and it worked perfectly.
It even worked perfectly when I ran it with electric fence to trap mis-use of allocated memory.
Then I ran it with test coverage, and now I see what the problem is.
Code:
5 fscanf(level, "%d", &room[i].numberofDialogs);
35 for(j = 0; j < 6; j++)
{
30 fscanf(level, "%d", &room[i].dir[j].numberOfDoors);
30 if(room[i].dir[j].numberOfDoors)
{
#### room[i].dir[j].door = malloc(sizeof(room[i].dir[j].door) * room[i].dir[j].numberOfDoors);
The #### means that line of code was never executed.
To me, this means that the fscanf for the numberOfDoors failed, and in doing so, left numberOfDoors uninitialised.
Now on my system, it looks like malloc is returning memory filled with zeros, because the if statement fails. So all the interesting inner loops which allocate more memory never get called here.
On your system, it looks like your malloc returns memory filled with junk, and anything non-zero will make your if statement succeed. This includes stupidly large and/or negative values which will definitely cause malloc to break.
In short, your code is extremely sensitive to the format of your file. A one character mistake anywhere and the whole lot comes crashing down. You definitely need a more robust way of reading files.
Something like this
> fscanf(level, "%d", &numberOfRooms);
Would be
Code:
char buff[BUFSIZ];
if ( fgets( buff, BUFSIZ, level ) != NULL ) {
if ( sscanf( buff, "%d", &numberOfRooms ) == 1 ) {
if ( numberOfRooms > 0 && numberOfRooms < MAX_ROOMS ) {
}
}
}
Even then, sscanf() can't detect integer overflow, so the most robust solution would use strtol().
--