How Unsafe is C#'s Unsafe Block?

Wednesday Aug 6th 2003 by Faisal Yousuf
Share:

A quick look at the C# unsafe keyword and the dangers of its use.

Environment: C#

C# is the language of .NET. Microsoft believes this is the most powerful and safest language around. Yaaa. It is a "remix" of Java with certain features such as Unsafe blocks to boost performance. But, there is the hack; Microsoft has tried to make conflicting goals meet with C# an example of which are unsafe blocks. C#'s unsafe blocks can render code that is as dangerous as C++. To see how, let's look at the following code:

public class AClass {
  public int aValueMember=0;
  private string _aRefMember="default";
  public string aRefMember
  {
    get {return _aRefMember;}
  }
}

Now, looking at this class, it may seem that the instance member _aRefMember's value="default" cannot be changed. If you think so, picture this...

public class Client {
  [STAThread]
  public static void Main(string[] arg) {
    AClass obj=new AClass();
    Console.WriteLine("Before Unsafe Block.................");
    Console.WriteLine("obj.aRefMember: ="+obj.aRefMember);
    unsafe {
      char* arrayPtr;
      fixed(int* ptr=&obj.aValueMember) {
        arrayPtr=(char*)(*(ptr-1));    // taking the address of
                                       // obj._aRefMember,
                                       // subtracting 1 becuase
                                       // the heap and stack grow
                                       // downwards in C#
                                       // this can be even nastier
                                       // *(ptr-1)=-1;
        arrayPtr[6]='D';               // first 6 bytes of the
                                       // string contains
                                       // information such as the
                                       // length of the string...
        arrayPtr[7] ='E';
        arrayPtr[8] ='F';
        arrayPtr[9] ='A';
        arrayPtr[10]='U';
        arrayPtr[11]='L';
        arrayPtr[12]='T';
      }

    }
    Console.WriteLine("After Unsafe Block.....");
    Console.WriteLine("obj.aRefMember: ="+obj.aRefMember);
  }
}

The Value of "obj.aRefMember" changed to "DEFAULT" from "default" ..... But, that's not all. You also can make the referance _aRefMember point to any location with this code:

  *(ptr-1)=XX;    // XX is any address be it legal or illegal

One thing that is encouraging is that if you assign an illegal address to the referance, the application will not crash but the CLR will raise a NullPointerException.

What the above code illustrates is that C#'s unsafe mechanism makes it as unsafe as C++. In principle, you can do many of the nasty things with it that you could do with C++, such as playing with the vTable and so forth.

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved