C# Attempted to read or write protected memory error
<p>Addendum: it seems to run correctly when I uncheck "optimize code" which leads me to believe it is some quirky configuration problem</p>

<p>Firstly I am trying to run unmanaged code.  I have "allow unsafe code" checked.  It is pointing to this line of code here where I am trying to read a bitmap without using the relatively slow getpixel:</p>

<pre><code>byte[] buff = { scanline[xo], scanline[xo + 1], scanline[xo + 2], 0xff };
</code></pre>

<p>Entire snippet is below. How can I correct this problem?</p>

<pre><code>private const int PIXELSIZE = 4;              // Number of bytes in a pixel

BitmapData mainImageData = mainImage.LockBits(new Rectangle(0, 0, mainImage.Width, mainImage.Height), ImageLockMode.ReadOnly, mainImage.PixelFormat);
List&lt;Point&gt; results = new List&lt;Point&gt;();

foundRects = new List&lt;Rectangle&gt;();

for (int y = 0; y &lt; mainImageData.Height
{
        byte* scanline = (byte*)mainImageData.Scan0 + (y * mainImageData.Stride);

        for (int x = 0; x &lt; mainImageData.Width; x++)
        {
            int xo = x * PIXELSIZE;
            byte[] buff = { scanline[xo], scanline[xo + 1], 
                    scanline[xo + 2], 0xff };
            int val = BitConverter.ToInt32(buff, 0);

            // Pixle value from subimage in desktop image
            if (pixels.ContainsKey(val) &amp;&amp; NotFound(x, y))
            {
                Point loc = (Point)pixels[val];

                int sx = x - loc.X;
                int sy = y - loc.Y;
                // Subimage occurs in desktop image 
                if (ImageThere(mainImageData, subImage, sx, sy))
                {
                    Point p = new Point(x - loc.X, y - loc.Y);
                    results.Add(p);
                    foundRects.Add(new Rectangle(x, y, subImage.Width,
                                                               subImage.Height));
                }
          }
        }
</code></pre>
