Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Mark as many functions as possible with the @safe annotation and try to compile. The compiler will tell you which functions failed the test.

  2. Use high-level constructs, such as foreach, references, and D array slices instead of low-level features such as pointers wherever possible.

  3. Instead of pointer arithmetic, use array...