全部
我使用以下函数来获取有关可用内存和堆中最大连续块的信息。
int GetLargestContiguousMemory()
{
MEMORY_BASIC_INFORMATION mbi;
DWORD start = 0;
bool recording = false;
DWORD freestart = 0, largestFreestart = 0;
__int64 free = 0, largestFree = 0; while (true)
{
// SIZE_T s = VirtualQueryEx(hproc, reinterpret_cast<lpvoid>(start), &mbi, sizeof(mbi));
SIZE_T s = VirtualQueryEx(GetCurrentProcess(), (void*)(start), &mbi, sizeof(mbi));
if (s != sizeof(mbi))
{
if (GetLastError() != ERROR_INVALID_PARAMETER)
//return ReportError(GetLastError(), _T("Failed to VirtualQueryEx at %08x"), start);
printf("Failed to VirtualQueryEx at %08x", start);
else
break;
}
if (mbi.State == MEM_FREE)
{
if (!recording)
freestart = start;
free += mbi.RegionSize;
recording = true;
}
else
{
if (recording)
{
if (free > largestFree)
{
largestFree = free;
largestFreestart = freestart;
}
}
free = 0;
recording = false;
}
start += mbi.RegionSize;
}
return largestFree;
}
int GetHeapAvailableMemory()
{
MEMORY_BASIC_INFORMATION mbi;
DWORD start = 0;
bool recording = false;
DWORD freestart = 0, largestFreestart = 0;
__int64 free = 0, largestFree = 0;
while (true)
{
// SIZE_T s = VirtualQueryEx(hproc, reinterpret_cast<lpvoid>(start), &mbi, sizeof(mbi));
SIZE_T s = VirtualQueryEx(GetCurrentProcess(), (void*)(start), &mbi, sizeof(mbi));
if (s != sizeof(mbi))
{
if (GetLastError() != ERROR_INVALID_PARAMETER)
//return ReportError(GetLastError(), _T("Failed to VirtualQueryEx at %08x"), start);
printf("Failed to VirtualQueryEx at %08x", start);
else
break;
}
if (mbi.State == MEM_FREE)
{
if (!recording)
freestart = start;
free += mbi.RegionSize;
}
start += mbi.RegionSize;
}
return free;
}
在我的程序中,我使用 operator new 循环分配内存,但是上面的函数多次迭代返回相同的值,并且返回值突然变化。它显示堆中可用内存的大小减少了 8M 字节。我无法理解。返回堆中可用内存大小的函数是否正确?
谢谢。跑步