How Unsafe is C#'s Unsafe Block?

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.



Comments

  • Billige GHD Rettetang Nettbutikk Gratis levering

    Posted by carpinteyroahs on 06/14/2013 05:53am

    [url=http://ghdrettetangtilbud.moonfruit.com/]ghd rettetang tilbud[/url] GHD rettetang sørger for at stylingen ikke blir for varm for farget hår. Det er faktisk ganske enkelt: Forskjellige hårtyper trenger forskjellige temperaturer for å reagere på styling. Varmen går lettere gjennom tynt hår enn tykt hår. Derfor har Satin Hair 7 Colour rettetang en intuitiv varmejustering som lar deg forhåndsinnstille temperaturen nøyaktig etter hårtypen (tynt, normalt, tykt hår). Og selv om du bruker effektknappen for å temme uregjerlige hårlokker, så vil du ikke utsette håret ditt for temperaturer på over 200 °C. Få flotte stylingresultater uten fare for for høye temperaturer og nyt den flotte hårfargen din lenger. [url=http://www.rettetangnorgenews.net/]ghd rettetang pris[/url] Hvis du noen gang har hatt en dårlig hårklipp eller stil du vil vite at hele utseende lider, kan det samme sies om det motsatte. Etter noen enkle retningslinjer kan ha håret bidra til å forbedre din generelle utseende og gi mer ungdommelig look.If du handler for rosa ghd, så du må være i stand til å jobbe ut forskjellen mellom en ekte rosa ghd og en falsk rosa ghd. [url=http://www.rettetangnorgenews.net/]rettetang ghd[/url] Gjør juledag og hver dag etter en god hair day med begrenset opplag ghd Metallic Collection gave set.Inspired av en ånd av julen, ser ghd Metallic samling den klassiske ghd V styler gitt en glamorøs make-over med en nydelig nye Rich Ruby Red skygge og blendende metallisk glans finish.Created med ghd flateste til dags dato, har den ghd Metallic Collection glitrende svart profilerte plater som glir uanstrengt gjennom håret – forlater din stil glatt og skinnende om du velger slanke og rett låser, sexy bølger eller store og bouncy krøller, akkurat hva du forventer med super kvalitet av noen ghd rettetang og Hårstylere.

    Reply
  • Jordan shoes mentioned Gene to pay off the discredit, a disunion of Nike

    Posted by TaddyGaffic on 04/20/2013 01:54am

    But in an e mail concerning the LSU activity from South Carolina on October 13, the faculty included the image but digitally erased the cross. The picture was in any other case untouched. A minimum of 15 folks have already been injured as Polish and Russian football enthusiasts clashed in Warsaw forward of your teams' 1-1 attract.. Once I have said, the soccer cleats by [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] Adidas have the similar characteristics, therefore in order to know all of them, then expect to have a lengthy list. Obviously, those are the same in ways that Adidas is the one brand that they carry. The lightness of the weight of the materials used in making the Adidas soccer cleats is definitely the main reason why the soccer cleats the manufacture and they are sold in the market are lightweight too. Pokhara is our base for this aerial playground. The [url=http://northernroofing.co.uk/roofins.cfm]nike free run[/url] choppy green hills all around offer a lifetime's worth of glorious flying possibilities, many of them still virgin. I Alpine (forward) launch, leaning forward, pulling my lines taut, with my glider laid out in an arc behind me. That is, you want something whose design is similar to that of a ski boot. That means that the inside removable liner, is a moldable type. ( it forms to the contours of your foot, providing maximum comfort and support.) You want the boot itself, made of a stiff plastic, or waterproof outer shell, again for support and insulation. Self defense purposes purposes dealing with #3 * Having the ability to contemplate [url=http://markwarren.org.uk/goodbuy.cfm]nike free uk[/url] gets and in addition leg techinques will not likely typically injure. I propose you will get out there applying reside training goods and rehearse fighting and also staying get to that has a close friend and even martial arts university undergraduate. Physical exercise diffusing strikes, using images, supplying photos, and in addition keeping crystal clear focused although becoming bombarded with plenty hits in addition to tennis shoes

    Reply
  • test

    Posted by waldo on 10/05/2012 01:43pm

    Seems we have a few Microsoft apologists in the audiance.

    Reply
  • Get a Life guys, he is just having his say

    Posted by Legacy on 08/19/2003 12:00am

    Originally posted by: 25yrVet

    Same as you guys can, no language is perfect, but surely needs to be discussed.

    Contribute dont denegrate

    Reply
  • *Yawn* Another MS Basher

    Posted by Legacy on 08/08/2003 12:00am

    Originally posted by: Microsoftie

    How unoriginal.

    Here's an idea - how about if you don't want unsafe code, you don't write any? I would rather have the option of/not using unsafe code than have a language designer decide for me. I like choice.

    Reply
  • What else would you expect?

    Posted by Legacy on 08/07/2003 12:00am

    Originally posted by: Warren Stevens

    I'm not trying to be too harsh towards the author, but...

    Is the fact that "unsafe" code actually turns out to be unsafe surprising to anyone???

    Reply
  • Another whimp ass Java programmer

    Posted by Legacy on 08/06/2003 12:00am

    Originally posted by: Sam Fugarino

    What's wrong with you people. You use the term "as dangerous as C++." All I can say is so what. You don't have to use unsafe code in C#.By the way, Java was designed with C++ in mind.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

  • As everyone scrambles to protect customers and consumers from the Heartbleed virus, there will be a variety of mitigating solutions offered up to address this pesky bug. There are a variety of points within the data path where solutions could be put into place to mitigate this (and similar) vulnerabilities and customers must choose the most strategic point in the network at which to deploy their selected mitigation. Read this white paper to learn the ins and outs of mitigating the risk of Heartbleed and the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds