Debugging heap corruption

Vladimir Panteleev thecybershadow at gmail.com
Sun Jul 29 19:23:18 PDT 2007


On Sun, 29 Jul 2007 17:02:08 +0300, Matthias Walter <walter at mail.math.uni-magdeburg.de> wrote:

> Leandro Lucarella Wrote:
>
>> Valgrind override both libc and system calls, and D's GC have to use them,
>> so my wild guess is *yes*, valgrind should help.
>
> Yes, valgrind works like a charm with D - except that D seems to not free all GC variables at the end, but this should be no problem. Memory corruption is still shown completely. Only problem I see here is if you have some errors in destructors, because then you'll see many corruptions evoked by GC-routines although the reasons are in your code.
> Also the symbol names are the mangled ones, so reading them is a bit odd.

Thanks for the replies. I'll clarify what I meant earlier regarding my assumptions about Valgrind not working with D as well as with C/C++ programs:

Consider this D program:

void main()
{
	ubyte[] a;
	a.length = 10;      // the allocated memory is in the GC-managed heap
	auto p = a.ptr;
	
	for(int i=0;i<=10;i++)
		*(p+i) = i;
}

In this case, the off-by-one error will go unnoticed, even when running under Valgrind. The same doesn't happen if you don't use the GC:

import std.c.stdlib;
void main()
{
	ubyte* p = cast(ubyte*)malloc(10);
	for(int i=0;i<=10;i++)
		*(p+i) = i;
}

malloc() wires directly to libc, which means that it will be recognized and instrumented by Valgrind - thus, the off-by-one error will be caught.

Of course, this doesn't mean that heap corruptions related to D's GC are untrace by Valgrind, as is displayed in practice. It's just that not all bugs, esp. minor (off-by-one) ones will be immediately detected with Valgrind. This sometimes causes the code to corrupt other parts of memory allocated via the GC, or even some of the GC's control structures, causing the program to crash as an indirect effect of the memory corruption (and making it impossible to find the original cause of the corruption). "Fixing" that would probably involve either teaching Valgrind to hook into D's GC, or using the built-in (albeit unfinished) SENTINEL debugging options mentioned in the original post.

I am currently running my program under Valgrind, waiting for some results, hoping for the best. Will post updates when will have some progress :)

-- 
Best regards,
  Vladimir                          mailto:thecybershadow at gmail.com



More information about the Digitalmars-d mailing list