程序在 fclose() 上崩溃

发布于 2024-10-30 20:54:30 字数 424 浏览 0 评论 0原文

我的程序在这部分代码上崩溃:

if(fclose(_device) != SUCCESS){  
    cerr << "Output device library error CLOSING FILE\n";  
    exit(1);  
}  

它不打印任何内容,当我写下这一行时:

cout << fclose(_device)<<endl;  

它也不打印任何内容,并且只是使我的程序崩溃而没有进一步的注释。

在程序的早期部分,我使用以下行初始化文件:

_device = fopen ((char*)filename , "a");  

什么会导致我的程序崩溃?

My program crashes on this part of code:

if(fclose(_device) != SUCCESS){  
    cerr << "Output device library error CLOSING FILE\n";  
    exit(1);  
}  

It doesn't print anything, and when i write instead this line:

cout << fclose(_device)<<endl;  

It doesn't print anything either, and just crashes my program with no further comments.

In an earlier part of my program, i initialize the file with this line:

_device = fopen ((char*)filename , "a");  

What can cause such a crash to my program?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绅刃 2024-11-06 20:54:30

此外,如果您的程序存在导致随机写入内存的错误,则可能是 fclose 需要用于关闭文件的信息被覆盖。

您可以尝试使用内存检查工具(例如 valgrind)来检查情况是否如此。

Also if your program has bugs which result in writing memory randomly, it might be that the information fclose needs to use to close the file gets overwritten.

You could try to use a memory checking tool, like valgrind, to check this is not the case.

最佳男配角 2024-11-06 20:54:30

之后,打开可能会失败

_device = fopen ((char*)filename , "a");  

检查 _device != NULL

编辑 由于您要检查 _device 在打开后是否有效,因此我倾向于使用调试器在打开时检查 _device 的值并将其与传递给 _fclose 的值进行比较。出于兴趣,_device 是否指向文件或通信设备,例如“COM2:”,因为这也可能对问题产生一些影响。最后,我将您的最终陈述分解如下:

int CloseResult = fclose(_device);
if (CloseResult != 0)
  cout << errno << CloseResult << endl;

原因是您不知道 fclose 或流输出是否是导致崩溃的原因。我假设您输出的流未链接到您尝试关闭的文件;)

Could be a failure on open, after

_device = fopen ((char*)filename , "a");  

check that _device != NULL

Edit Since you are checking that _device is valid after being opened, I'd tend to use the debugger to check the value of _device on opening and compare it to the value being passed to _fclose. Out of interest, is _device pointing to a file or a comms devices such as "COM2:" as this could also have some bearing on the problem. Lastly, I'd break down your final statement as follows;

int CloseResult = fclose(_device);
if (CloseResult != 0)
  cout << errno << CloseResult << endl;

Reason for this is that you don't know if the fclose or stream output is the cause of your crash. I'm assuming that the stream your outputting to isn't linked to the file your trying to close ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文