Can't obtain accurate information of available

2019-09-09 12:20发布

all

I use the following function to obtain information about available memory and largest contiguous block in the heap.

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

In my program, I use operator new to allocate memory in a loop, but the above function return same value for several iterations, and the returned value changes suddenly. It shows the size of the available memory in the heap is reduced by 8M bytes. I can't understand that. Is the function correct to return the size of available memory in the heap?

Thanks. Jogging

0条回答
登录 后发表回答