how to debug memory errors

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Nov 6 18:22:35 PST 2016


On 11/6/16 5:15 PM, Lodovico Giaretta wrote:
> On Sunday, 6 November 2016 at 21:46:52 UTC, Øivind wrote:
>> Hi,
>>
>> My app occasionally gives me a
>>
>> *** Error in `./hauto-test': double free or corruption (fasttop):
>> 0x00007f504c002a60 ***
>>
>> but gives me the following on every termination
>>
>> core.exception.InvalidMemoryOperationError at src/core/exception.d(693):
>> Invalid memory operation
>>
>> How do I go about debugging and resolving these?
>>
>> -Øivind
>
> I think that "Invalid Memory Operation" is the error the GC gives you
> when you try to allocate memory during the collection phase (i.e. inside
> a destructor). I suggest you avoid doing so.
>
> I don't know if the double free problem is related to this. It may as
> well be a totally unrelated bug of some container you are using.

It absolutely could be related to this.

Imagine a resource wrapper like so:

class Foo
{
    int *mem;
    this() { mem = cast(int *)malloc(int.sizeof); }
    ~this() { .free(mem); }
}

Now, you have a problem if you do something like this:

class Bar
{
    Foo foo;
    ~this() { delete foo; }
}

Whenever Bar's dtor is called, it's going to throw the error when the 
delete call tries to free the block.

However, occasionally, the GC will have destroyed the foo instance 
BEFORE destroying the Bar instance that holds it. This will result in 
Foo's dtor being called twice for the same memory, resulting in the 
double-free call. Then of course, the memory free of the GC is not 
allowed, so we have the exception happening after.

OP: it's not legal to destroy or even access GC allocated members in a 
destructor. The GC may have already destroyed that data. I would 
recommend printing the stack trace when you get the exception, and 
figure out where the culprit is.

-Steve


More information about the Digitalmars-d-learn mailing list