Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you delete a FILE object created from fopen?

Tags:

c++

fopen

While investigating a crash, I came across this code:

FILE * RejectFile = fopen("filename", "a+");
// other code happens
delete RejectFile;

My understanding is that you only call delete on objects that were created by new. Granted some of this old code is really bad so it's likely this is wrong, but I'm not sure. Is this valid code?

like image 667
Jesse Jashinsky Avatar asked Sep 08 '14 23:09

Jesse Jashinsky


2 Answers

No, this is not valid. Only ever use delete on pointers obtained via new. What happens here is undefined behavior; it might work, it might crash, it might output garbage, it might start playing some music...

You need to use fclose() to destroy the file handle.

like image 177
cdhowie Avatar answered Sep 30 '22 05:09

cdhowie


If you really need to use delete, you can use some wrappers around these constructs. Like,

class MyFILE
{
public:
    MyFILE(/*file params*/);
    virtual ~MyFILE(){fclose(_fileptr);
private:
    FILE * _fileptr;
}

A sample usage would be,

MyFILE * f = new MyFILE(/*file params*/);
delete f;

Personally, I prefer this wrapper solution, since it provides a comprehensive way to manage resources. For an example, when we on a code segment where exceptions can be thrown any time by any part of it. If we have allocated resources like open files, this mechanism opens up way to 'automatically' delete the object when the wrapper goes it out of the scope.

like image 23
Doonyx Avatar answered Sep 30 '22 04:09

Doonyx