开发者

FILE pointer mysteriously resetting to NULL

I'm using visual stduio 2008 c++. And I'm writing windows form application. I declare a FILE* array at the top of Form1.h as a global value

const int k = 1; //i need to change k to 2 sometimes. 
FILE* myFiles[k]; 

In From1's constructor, I use a for loop to fopen my files.

for(int i = 0; i < k; ++i)
{    
  char filename[100] = "";
  sprintf(filename,"Record/record_%ld_%d.txt",g_recordName,i);
  myFiles[i] = fopen(filename,"w");
}

And I set a timer for this form, each tick it will fprintf something into myFiles. It's fine so far, but if I put s开发者_运维百科omething like

fprintf(myFiles[0],"%d",1234); 

into constructor after the for-loop. It works OK this line, but if I'm gonna fprintf anything in timer's tick event, I found that myFiles[0] is already set to NULL!!

In addition, if I fprintf(myFiles[0],"something") in the construtor, FILE pointer still won't be null in timer's tick event.

WHY does this happen?! anyone knows why?


A very simple case of buffer overrun. The expression sprintf(filename,"Record/record_%ld_%d.txt",g_recordName,i); is most probable the culprit.


Really thanks to Ajay's help! Yes, this problem (buffer over-run) is caused by sprintf, fprintf. Seems like they are pretty vulnerable. So I changed my code using C++ like stuff - iostream and fstream. Now, it works on me. :) Thank you again.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜