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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With