Per Erik Strandberg /cv /kurser /blog

The code

We create a small program that creates an array with four integers. Inside it we use a C-style pointer and print items outside of our array. This is ok since it we are using the keyword unsafe.

public class Program
{
  unsafe public static void Main()
  {
    // Create an array of 4 integers.
    int[] array = new int[4];
    for (int i = 0; i < 4; i++)
      array[i] = i * i;

    Console.WriteLine("Display 6 items (oops!):");
    fixed (int* ptr = array)
      for (int j = 0; j < 6; j++)
        Console.WriteLine(*(ptr + j));

    Console.WriteLine("Display all items:");
    foreach (int k in array)
      Console.WriteLine(k);


    // this throws an exception upon compilation
    // Console.WriteLine(array[54]);

  }
}

Compilation

We must use /unsafe when compiling.

csc /unsafe illegal_array.cs

Output

As you might have guessed this is bad use of pointers. The fifth and sixth value printed are (I guess) pretty random. With a little bit of luck the .NET platform might store some extra information somewhere around the object - but where that information is (if is it before/after the object (or somewhere completely different) I do not know. Also the location will/might most likely change with different versions of .NET.).

>illegal_array.exe
Display 6 items (oops!):
0
1
4
9
0
2031066136
Display all items:
0
1
4
9


This page belongs in Kategori Programmering.