abhinavkulkarni
abhinavkulkarni

Reputation: 2399

Double free error on fclose() on previously closed file handle

I have a class that contains file handle fHandle that points to an open file. Now, it can be closed by any one of the multiple routines and that is based on dynamic run of the program.

To be sure that a file is indeed closed, I put simple snippet in my destructor: if(fHandle!=NULL) fclose(fHandle);. Turns out, if one of the routines had previously closed this file, then the running the destructor snippet causes double free operation and I get **glib detected** error message.

How do I make sure that I don't close the file handle that has previously been closed (apart from putting NULL check)?

Upvotes: 0

Views: 3049

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106096

You say you've tried:

if(fHandle!=NULL) fclose(fHandle);

To avoid a double fclose(), just set fHandle to NULL whereever else you may call fclose on that handle, so the above code in the destructor won't pass the conditional test....

Upvotes: 1

Jay
Jay

Reputation: 24895

fclose doesn't set the fhandle to NULL. So, after calling fclose if you set the fhandle to NULL explicity it should solve your problem.

Your code should be something like below:

if(NULL != fhandle)
{
   fclose(fhandle);
   fhandle = NULL;
}

Note: This solution will not work if your function that calls close is called from multiple threads.

Upvotes: 1

Karthik T
Karthik T

Reputation: 31952

Is this specifically C or C++. One easy fix for your latter issue to use a seperate flag to check if the file is closed or not? Something like this

void CloseFile(){
  if(flag ==0){
    fclose(fHandle);
      flag =1;
  }
}

If this is for c++ you can encapsulate the file handle inside a class and use RAII to automatically call the close just once by adding that call in the class's destructor. You could also (not recommended) not do RAII and merely encapsulate the flag within the same class if you want to go that way, and call close manually.

Upvotes: 0

Related Questions