Marshal.Copy method throws AccessViolationException in C#.NET

Arvind K picture Arvind K · Mar 24, 2009 · Viewed 11.1k times · Source

I am working on a C# application that would display live images from a camera. The problem I am facing with the following code snippet is that, I get AccessViolationException in Marshal.Copy when running this function executed continuously in a thread. But, this runs successfully when run once (I get a single static image). I guess it has to do with some memory corruption issue. Any idea/suggestions on how to deal with this problem?

    private Image ByteArrayToImage(byte[] myByteArray) 
    {
        if (myByteArray != null)
        {
            MemoryStream ms = new MemoryStream(myByteArray);
            int Height = 504;
            int Width = 664;
            Bitmap bmp = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
            BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
            Marshal.Copy(myByteArray, 0, bmpData.Scan0, myByteArray.Length);
            bmp.UnlockBits(bmpData);

            return bmp;
        }
        return null;
    }

Answer

morechilli picture morechilli · Mar 24, 2009

It looks to me like you are always trying to copy the number of bytes myByteArray.Length to the bitmap buffer.

You are not checking that the bitmap buffer is in fact as big as that - so are probably writing off the end of the bitmap buffer.

Try checking if myByteArray.Length is ever greater than bmpData.Stride x bmp.Height

If this is the case you'll need to relook at the assumptions you've made with your hard coded values for width, height and pixel format.