How to fix "Access Violation Exception" when accessing ImageHlp.MapFileAndCheckSumA?

0

I declare it as:

        [System.Runtime.InteropServices.DllImport("imagehlp.dll")]

        public static extern UInt32 MapFileAndCheckSumA(string fileName,
            IntPtr HeaderSum,
            IntPtr CheckSum);

Then I try to call MapFileAndCheckSumA

        IntPtr HeaderSum = new IntPtr(0);
        IntPtr CheckSum = new IntPtr(0);
        UInt32 status= ImageHlp.MapFileAndCheckSumA("19_02_21.exe", HeaderSum, CheckSum);

        Console.WriteLine(status);
        Console.WriteLine(CheckSum.ToInt32());
        Console.ReadLine();

But I get this error pointing to ImageHlp.MapFileAndCheckSumA(.....):

System.AccessViolationException
  HResult=0x80004003
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

I think I have done a very simple but obvious mistake.

Correction: The error was thrown because my code above was trying to allocate at memory location 0x0.

The proper way of using IntPtr() is:

    int HeaderSum = 0;
    int CheckSum = 0;
    IntPtr ptrHeaderSum=Marshal.AllocHGlobal(sizeof(int));
    Marshal.WriteInt32(ptrHeaderSum, HeaderSum);
    IntPtr ptrCheckSum = Marshal.AllocHGlobal(sizeof(int));
    Marshal.WriteInt32(ptrCheckSum, CheckSum);
    UInt32 status= ImageHlp.MapFileAndCheckSumA(@"D:\19_02_21.exe", ptrHeaderSum, ptrCheckSum);

    Console.WriteLine(status);
    CheckSum = Marshal.ReadInt32(ptrCheckSum);
    Console.WriteLine(CheckSum);

    Marshal.FreeHGlobal(ptrHeaderSum);
    Marshal.FreeHGlobal(ptrCheckSum);
    Console.ReadLine();
c#
pinvoke
portable-executable
asked on Stack Overflow Jun 10, 2020 by Mussel • edited Jun 21, 2020 by dbc

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0