Most efficient replacement for IsBadReadPtr?

前端 未结 10 1286
你的背包
你的背包 2020-12-06 06:45

I have some Visual C++ code that receives a pointer to a buffer with data that needs to be processed by my code and the length of that buffer. Due to a bug outside my contro

10条回答
  •  难免孤独
    2020-12-06 07:18

    The fastest solution I can think of is to consult the virtual memory manager using VirtualQuery to see if there is a readable page at the given address, and cache the results (however any caching will reduce the accuracy of the check).

    Example (without caching):

    BOOL CanRead(LPVOID p)
    {
      MEMORY_BASIC_INFORMATION mbi;
      mbi.Protect = 0;
      ::VirtualQuery(((LPCSTR)p) + len - 1, &mbi, sizeof(mbi));
      return ((mbi.Protect & 0xE6) != 0 && (mbi.Protect & PAGE_GUARD) == 0);
    }
    

提交回复
热议问题