FILE 指针神秘地重置为 NULL
我正在使用 Visual stduio 2008 c++。我正在编写 Windows 窗体应用程序。我在 Form1.h 顶部声明一个 FILE* 数组作为全局值。
const int k = 1; //i need to change k to 2 sometimes.
FILE* myFiles[k];
在 From1 的构造函数中,我使用 for 循环来打开我的文件。
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");
}
我为此表单设置了一个计时器,每次滴答都会将某些内容打印到 myFiles 中。 到目前为止还不错,但如果我
fprintf(myFiles[0],"%d",1234);
在 for 循环之后将类似的内容放入构造函数中。这行工作正常,但是如果我要在计时器的滴答事件中打印任何内容,我发现 myFiles[0] 已经设置为 NULL!
另外,如果我在构造函数中fprintf(myFiles[0],"something")
,在计时器的tick事件中FILE指针仍然不会为空。
为什么会发生这种情况?有人知道为什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
缓冲区溢出的一个非常简单的情况。表达式
sprintf(filename,"Record/record_%ld_%d.txt",g_recordName,i);
很可能是罪魁祸首。A very simple case of buffer overrun. The expression
sprintf(filename,"Record/record_%ld_%d.txt",g_recordName,i);
is most probable the culprit.真的很感谢阿杰的帮助!是的,这个问题(缓冲区溢出)是由sprintf、fprintf引起的。看起来他们很脆弱。所以我使用 C++ 之类的东西更改了我的代码 - iostream 和 fstream。现在,它对我有效。 :) 再次感谢您。
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.