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 something 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.