Segmentation fault on closing file in destructor
Michel Fortin
michel.fortin at michelf.com
Sun Sep 26 17:20:18 PDT 2010
On 2010-09-26 10:06:33 -0400, "Simen kjaeraas" <simen.kjaras at gmail.com> said:
> Tom Kazimiers <2voodoo at gmx.de> wrote:
>
>> 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?
>
> Likely, it is this[1]:
>
> "[T]he order in which the garbage collector calls destructors for
> unreference objects is not specified. This means that when the garbage
> collector calls a destructor for an object of a class that has members
> that are references to garbage collected objects, those references may
> no longer be valid. This means that destructors cannot reference sub
> objects."
>
> [1]: http://digitalmars.com/d/2.0/class.html#destructors
That's it indeed, but I'll add that it's the File struct that is at
fault. See this bug:
<http://d.puremagic.com/issues/show_bug.cgi?id=4624>
To make it short: when the File struct is located somewhere in the GC
heap (like inside a class), File's destructor is buggy when a file is
open. The only workaround I can think of is to call close() or detach()
on the file struct before the garbage collectors kicks in (doing it in
the destructor of your class is already too late, it must be done
before the destructor gets called).
In fact, it's generally a good idea to not wait for the GC to collect
your objects before closing files, because waiting for the GC could
take an indeterminate amount of time and leave files open for a long
time (the GC only runs when needed).
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the Digitalmars-d-learn
mailing list