Preventing memory corruption bugs with @safe
Memory corruption bugs are one of the most frustrating problems a C programmer can encounter. Memory corruption is writing to what you believed was memory owned by one object; it affects another object in unpredictable ways, leading to crashes. D aims to reduce the scope and occurrence of these bugs by providing a statically checked memory-safe subset which, ideally, exhibits no undefined behavior. In practice, @safe
isn't perfect due to bugs in the specification and the implementation, but it nevertheless helps to significantly reduce the probability of memory corruption bugs.
How to do it…
Perform the following steps by using @safe
:
Mark as many functions as possible with the
@safe
annotation and try to compile. The compiler will tell you which functions failed the test.Use high-level constructs, such as
foreach
, references, and D array slices instead of low-level features such as pointers wherever possible.Instead of pointer arithmetic, use array...