Can you spot the overflow…?

 1 using System;   
 2     
 3   namespace UnsafeCode   
 4   {   
 5      public class Program   
 6      {   
 7          public static unsafe void Main( )   
 8          {   
 9              Int32[] array = new int[4];  
10              for( int i = 0; i < 4; i++ ) {  
11                  array[ i ] = i * i;  
12              }  
13              Console.WriteLine( "Display 6 items (oops!)" );  
14    
15              fixed( Int32* ptr = array ) {  
16                  for( int j = 0; j < 6; j++ ) {  
17                      Console.WriteLine( *( ptr + j ) );  
18                  }  19:              }  
19              Console.WriteLine( "Display all items" );  
20              foreach( int k in array ) {  
21                  Console.WriteLine( k );  
22              }  
23          }  
24      }  
25   }

Pretty cool hey… you can use pointer in C#. You have to do a couple things though, in order to get it to work.

  1. You have declare the block of code as unsafe
unsafe ... { }
  1. You have to tell the C# compiler to allow unsafe code. You can do this with the /unsafe switch or check the checkbox in the project settings.

  1. You will also have to pin the objects you are pointing to, so that the garbage collector does not reclaim that memory. Use the fixed keyword. The following will pin the array so that it does not get reclaimed by the garbage collector.
fixed( Int32* ptr = array ) {

  }

Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (Microsoft .NET Development Series) by Krzysztof Cwalina, Brad Abrams

Read more about this title…

comments powered by Disqus