Segmentation fault on closing file in destructor

Tom Kazimiers 2voodoo at gmx.de
Sun Sep 26 04:38:15 PDT 2010


Hi,

a file reading class of mine can be constructed with a filename as
parameter. It instantiates a new std.stream.File (without the passed
file name and closes it when opened within the destructor. The last part
is where things are getting unclear for me. On the "file.isOpen()" call
in the destructor a segmentation fault occurs. What is the problem with
that?

Thanks in advance,
Tom

An example class to demonstrate the problem:

import std.stdio;
import std.string;
import std.stream;

class FileReader(T) {
    string          filename; // the name of the object file
    std.stream.File file;     // the object file

  public:
    this(string filename) {
        // make an immutable copy of the filename
        this.filename = filename.idup;
        file = new std.stream.File();
    }

    // destructor
    ~this() {
        if(file.isOpen())  // <---- crashes here
            writefln("open");
    }
	
    // open file, return true if successful
    bool open() {
        try {
            file = new std.stream.File(filename, FileMode.In);
        } catch(OpenException e) {
            writefln("[Error] Could not open file: " ~ filename);
            return false;
        }
        return true;
    }
}


More information about the Digitalmars-d-learn mailing list