Can you delete a FILE object created from fopen?

During the accident investigation, I came across this code:

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

I understand that you only call delete on objects created by new . Of course, some of this old code is really bad, so it's probably wrong, but I'm not sure. Is this a valid code?

+7
c ++ fopen
source share
2 answers

No, this is not true. Use delete only pointers obtained with new . This is where undefined behavior occurs; it can work, it can fall, it can take out the trash, it can start playing music ...

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

+14
source share

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

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

Using an example will

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

Personally, I prefer this shell solution, as it provides an exhaustive way to manage resources. For example, when we are on a code segment where exceptions can be thrown at any time on any part of it. If we allocate resources, such as open files, this mechanism opens the way to β€œautomatically” delete the object when the shell goes out of scope.

+4
source share

All Articles