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

强颜欢笑 提交于 2019-12-25 05:25:09

问题


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


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/12811464/double-free-error-on-fclose-on-previously-closed-file-handle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!