Segmentation fault on closing file in destructor

Steven Schveighoffer schveiguy at yahoo.com
Mon Sep 27 05:09:04 PDT 2010


On Sun, 26 Sep 2010 20:20:18 -0400, Michel Fortin  
<michel.fortin at michelf.com> wrote:

> 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>

He's using std.stream.File, not std.stdio.File.

> 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).

Yes, this is true no matter what File construct you use.

-Steve


More information about the Digitalmars-d-learn mailing list