NtFreeVirtualMemory and VirtualFree (64bit)

Arsium ***** 331 Reputation points
2021-07-11T21:12:42.793+00:00

Hello,

I'm implementing and testing myself native api but I got some problems with NtFreeVirtualMemory.

NtFreeVirtualMemory(Process.GetCurrentProcess().Handle, ptr, 0, 0x00008000); //doesn't work from ntdll

VirtualFree(ptr , (uint)0, 0x00008000); // from kernel32

I don't know why NtFreeVirtualMemory returns always access violation whereas VirtualFree works and frees the memory (I've inspected with ProcessHacker)

Any idea ?

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,413 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,215 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 81,481 Reputation points
    2021-07-11T22:48:47.097+00:00

    This works for me =>

    IntPtr pBaseAddress = IntPtr.Zero;
    uint pSize = 4096;
    uint nStatus = NtAllocateVirtualMemory(Process.GetCurrentProcess().Handle, ref pBaseAddress, IntPtr.Zero, ref pSize, MEM_RESERVE, PAGE_READWRITE);
    if (nStatus == 0)
    {
        nStatus = NtFreeVirtualMemory(Process.GetCurrentProcess().Handle, ref pBaseAddress, ref pSize, MEM_RELEASE);
    }
    

    Declarations :

    [DllImport("NtDll.dll", SetLastError = true)]
    private static extern uint NtAllocateVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, IntPtr ZeroBits, ref uint RegionSize, uint AllocationType, uint Protect);
    
    [DllImport("NtDll.dll", SetLastError = true)]
    private static extern uint NtFreeVirtualMemory(IntPtr ProcessHandle, ref IntPtr BaseAddress, ref uint RegionSize, uint FreeType);
    
    public const int MEM_COMMIT = 0x00001000;
    public const int MEM_RESERVE = 0x00002000;
    public const int MEM_DECOMMIT = 0x00004000;
    public const int MEM_RELEASE = 0x00008000;
    
    public const int PAGE_NOACCESS = 0x01;
    public const int PAGE_READONLY = 0x02;
    public const int PAGE_READWRITE = 0x04;
    
    0 comments No comments