是否可以在不引发C ++异常的情况下检查内存块是否可读?

c00*_*0fd 1 c++ windows winapi memory-management

对于C ++代码中的异常处理程序,我需要以下内容。说,我有以下代码块:

void myFunction(LPCTSTR pStr, int ncbNumCharsInStr)
{
    __try
    {
        //Do work with 'pStr'

    }
    __except(1)
    {
        //Catch all

        //But here I need to log `pStr` into event log
        //For that I don't want to raise another exception
        //if memory block of size `ncbNumCharsInStr` * sizeof(TCHAR)
        //pointed by 'pStr' is unreadable.
        if(memory_readable(pStr, ncbNumCharsInStr * sizeof(TCHAR)))
        {
            Log(L"Failed processing: %s", pStr);
        }
        else
        {
            Log(L"String at 0x%X, %d chars long is unreadable!", pStr, ncbNumCharsInStr);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么办法可以实施memory_readable

tor*_*rak 5

VirtualQuery来功能也许能帮助。以下是如何memory_readable使用它的快速入门。

bool memory_readable(void *ptr, size_t byteCount)
{
  MEMORY_BASIC_INFORMATION mbi;
  if (VirtualQuery(ptr, &mbi, sizeof(MEMORY_BASIC_INFORMATION)) == 0)
    return false;

  if (mbi.State != MEM_COMMIT)
    return false;

  if (mbi.Protect == PAGE_NOACCESS || mbi.Protect == PAGE_EXECUTE)
    return false;

  // This checks that the start of memory block is in the same "region" as the
  // end. If it isn't you "simplify" the problem into checking that the rest of 
  // the memory is readable.
  size_t blockOffset = (size_t)((char *)ptr - (char *)mbi.AllocationBase);
  size_t blockBytesPostPtr = mbi.RegionSize - blockOffset;

  if (blockBytesPostPtr < byteCount)
    return memory_readable((char *)ptr + blockBytesPostPtr,
                           byteCount - blockBytesPostPtr);

  return true;
}
Run Code Online (Sandbox Code Playgroud)

注意:我的背景是C,所以尽管我怀疑有比char *在C ++中强制转换为更好的选择,但我不确定它们是什么。