gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:13:05 24 4
gpt4 key购买 nike

我需要以下 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);
}
}
}

有没有办法实现memory_readable

最佳答案

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;
}

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

关于c++ - 我可以在不引发 C++ 异常的情况下检查内存块是否可读吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com