Some memory safety

bearophile bearophileHUGS at lycos.com
Wed May 20 02:30:38 PDT 2009


Walter Bright:

Sorry for raising this thread.
While C# has purposes somewhat different from D, I think C# designers are right in their emphasys on safety. Modern programmers appreciate some safeties, and modern languages give them. The ideas I am talking about are already implemented in C#.
D can disable such safeties in release mode.

For example this C# code, compiled in release + unsafe mode shows that the dotnet stops the execution almost as soon you write out of the allowed memory zone. This uses stackalloc (similar to alloca) so they may be using a stack canary to detect the out of bound condition at runtime:
http://en.wikipedia.org/wiki/Stack_buffer_overflow#Stack_canaries

using System;
public sealed unsafe class Test {
  static void Main(string[] args) {
    int n = args.Length > 0 ? Int32.Parse(args[0]) : 10;
    int* a = stackalloc int[n];
    for (int i = 0; i < n * 2; i++) {
      a[i] = i;
      Console.WriteLine("{0}", a[i]);
    }
  }
}


>D is not going to catch memory safety problems that result from using C library functions, like malloc. D can only guarantee memory safety when using D code and D library functions. The programmer is on his own using the unsafe C functions.<

When I port C code to D I'd like the D compiler help me catch some of the memory bugs that may be present in the translated C code.
In C you have www.splint.org and valgrind, but the Java compiler shows how much good is to have a stricter compiler in the first place.

And in D code you have array.ptr and std.gc.malloc too (and std.c.stdlib.alloca, that is a C function but has no equivalent to D, so I can think of it as part of D), such things may lead to bugs. Such things may be totally disallowed in "safe" D modules, but some safety may be added to unsafe D modules too.

For example the memory std.gc.capacity() of Phobos1 can be used to detect out of bound situations with pointers given by std.gc.malloc.

Bye,
bearophile



More information about the Digitalmars-d mailing list