If you are a C or C++ programmer, you might be a bit apprehensive after reading the previous section because you know that misuse of pointers in your programs can cause your programs to crash. DTrace, however, is a robust, safe environment for executing your D programs. Take note that these types of mistakes cannot cause program crashes. You might write a buggy D program, but invalid D pointer accesses do not cause DTrace or the operating system kernel to fail or crash in any way. Instead, the DTrace software detects any invalid pointer accesses, disables your instrumentation, and reports the problem back to you for debugging.
If you have previously programmed in the Java programming language, you are probably aware that the Java language does not support pointers for precisely the same reasons of safety. Pointers are needed in D because they are an intrinsic part of the operating system's implementation in C, but DTrace implements the same kind of safety mechanisms that are found in the Java programming language to prevent buggy programs from damaging themselves or each other. DTrace's error reporting is similar to the runtime environment for the Java programming language that detects a programming error and reports an exception.
To observe DTrace's error handling and reporting, you could
write a deliberately bad D program using pointers. For example,
in an editor, type the following D program and save it in a file
named badptr.d
:
BEGIN { x = (int *)NULL; y = *x; trace(y); }
The badptr.d
program creates a D pointer
named x
that is a pointer to
int
. The program assigns this pointer the
special invalid pointer value NULL
, which is
a built-in alias for address 0. By convention, address
0
is always defined as invalid so that
NULL
can be used as a sentinel value in C and
D programs. The program uses a cast expression to convert
NULL
to be a pointer to an integer. The
program then dereferences the pointer by using the expression
*x
, assigns the result to another variable
y
, and then attempts to trace
y
. When the D program is executed, DTrace
detects an invalid pointer access when the statement y
= *x
is executed and reports the following error:
#dtrace -s badptr.d
dtrace: script 'badptr.d' matched 1 probe dtrace: error on enabled probe ID 1 (ID 1: dtrace:::BEGIN): invalid address (0x0) in action #2 at DIF offset 4^C
#
Notice that the D program moves past the error and continues to
execute; the system and all observed processes remain
unperturbed. You can also add an ERROR
probe
to your script to handle D errors. For details about the DTrace
error mechanism, see Section 11.1.3, “ERROR Probe”.