Zach
Zach

Reputation: 537

Program crashes on fclose()

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?

Upvotes: 0

Views: 2126

Answers (2)

SmacL
SmacL

Reputation: 22922

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 ;)

Upvotes: 2

vladmihaisima
vladmihaisima

Reputation: 2248

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.

Upvotes: 2

Related Questions