开发者

problem with fprintf

I am running a simulation in C, and need to store 3 100x100 matrices ~1000 times. My program runs just fine when I'm not writing the data to file. But when I run my program and write the data, I get a segmentation error after 250 time steps or so. And I don't understand why.

My save function looks like this

void saveData(Simulation* sim, int number) {
   sprintf(pathname_vx, "data/xvel%d.dat", number);
   sprintf(pathname_vy, "data/yvel%d.dat", number);
   sprintf(pathname_rho, "data/rho%d.dat", number);
   FILE* vx_File = fopen(pathname_vx, "w");
   FILE* vy_File = fopen(pathname_vy, "w");
   FILE* rho_File = fopen(pathname_rho, "w");
   int iX, iY;
   double ux, uy, rho;
   for (iY=0; iY<sim->ly; ++iY) {
       for (iX=0; iX<sim->lx; ++iX) {
           computeMacros(sim->lattice[iX][iY].fPop, &rho, &ux, &uy);
           fprintf(vx_File, "%f ", ux);
           fprintf(vy_File, "%f ", uy);
           fprintf(rho_File, "%f ", rho);
       }
       fprintf(vx_File, "\n");
       fprintf(vy_File, "\n");
       fprintf(rho_File, "\n");
   }
   fclose(vx_File);
   fclose(vx_File);
   fclose(vy_File);
}

where 'Simulation' is a struct containing a lattice (100x100 matrix) with 3 different variables 'rho', 'ux', 'uy'. The 'number' argument is just a counting variable to name the files correctly.

开发者_高级运维

gdb says the following, but it doesn't help me much.

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000010
0x00007fff87c6ebec in __vfprintf ()

I'm not that experienced in programing, so I guess there are better ways to write data to file. Any attempt to clarify why my approach doesn't work is highly appreciated.

Thanks

jon


Looks like you're closing vx_File twice, and not closing rho_File at all. This means that you're leaving rho_File open each iteration, and thus using up a file descriptor each time through.

I'd guess the program fails you're running out of file descriptors. (Since this happens on the 250'th iteration, I'd guess your limit is 256). Once you're out of file descriptors, one of the fopen() calls will return NULL. Since you don't check the return value of fopen(), the crash will occur when you attempt to fwrite to a NULL handle.


Looks like a NULL pointer dereference. You need to check the result of fopen() to make sure it succeeded (non-NULL result).


Maybe you run out of memory when you are creating those thousand 100x100 matrices (or whatever is exactly happening). You could then end up with a incomplete sim->lattice that might contain NULL pointers.

Do you check if you malloc() calls succeed? If they can't allocate memory they return NULL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜