无法获取堆中可用内存的准确信息

时间:2012-05-21 07:25:42

标签: c++ memory-management new-operator

所有

我使用以下函数来获取有关堆中可用内存和最大连续块的信息。

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字节。 我无法理解。函数是否正确以返回堆中可用内存的大小?

感谢。 慢跑

0 个答案:

没有答案