How D intercepts runtime errors

Serg Kovrov user at domain.invalid
Thu Jul 27 06:52:50 PDT 2006


I am quite exited by how D handling runtime errors. For example bad
pointer dereferencing.

Consider simple C/C++ example (I used try catch blocks just to
illustrate an idea):
> #include <stdio.h>
> int main(int argc, char *argv[])
> {
> 	char h[] = "hello";
> 	char *p = h;
> 	p = (char*)123; // me evil hax0r
> 	try
> 	{
> 		printf("pointer is %d\n", p);
> 		printf("value is %s\n", p);
> 	}
> 	catch (...)
> 	{
> 		printf("gotcha!");
> 	}
> 	return 0;
> }
Sure it chases.

And here is equivalent code in D:
> import std.stdio;
> int main(char[][] args)
> {
> 	char[] h = "hello";
> 	char[]* p = &h;
> 	p = cast(char[]*)0x123; // me evil hax0r
> 	try
> 	{
> 		writefln("pointer is %d", p);
> 		writefln("value is %s", *p);
> 	}
> 	catch (Exception e)
> 	{
> 		writef("gotcha!");
> 	}
> 	return 0;
> }
Which (to my admiration) somehow works =)
And I'm wondering how it works.

I'm more or less understand what happen in C/C++ when incorrect pointer
being dereferenced. But could someone kindly explain to me how it works
in D, please?

I mean, who (and how) is checking pointer I try to use, who throws
exception, etc.. I is it garbage collector routine injected into my
executable, or some other part of standard library, or maybe something
completely different...

And of course, how it could affect performance.


Ah, there is some more. Is there something D could not intercept? I mean
is there a way to crash/segfault program? Kinda silly question, yes. But
knowing that could help to avoid it.

Thanks.



More information about the Digitalmars-d mailing list