Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find largest allocation of memory possible

In 32bit mode application has access to 2GB of virtual address space. How would you find out the maximum size of memory you can allocate to this virtual address space, without malloc or new failing?

For example, lets say you want to take up the whole 2GB of virtual address space, but you just allocated 2MB of data in the middle of the 2GB address space. Is there a Windows API call that you can find out the max concurrent address space that you can allocate? So that when you call malloc or new the call does not fail?

Thank you for your time.

like image 523
Chad Avatar asked Feb 26 '23 09:02

Chad


2 Answers

Source: http://www.voyce.com/index.php/2009/08/21/largest-free-block-of-address-space/

DWORD FindLargestSizeOfMemory()
{

    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 = VirtualQuery((LPCVOID)start, &mbi, sizeof(mbi));
        if (s != sizeof(mbi)) 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;
}
like image 82
Chad Avatar answered Feb 27 '23 23:02

Chad


You might never get a satisfactory answer. The largest allocatable memory block is dependend on memory fragmentation and can be altered with memory defragmentation tools, different memory managers, different boot time switches (e.g. /3GB on windows) or even a reboot.

I'm not sure what you mean by "without malloc or new failing", do you not have access to malloc? Because the correct way to do this would be to allocate memory using var=malloc(...) in incrementing steps and looking for the step where var is null.

I am pretty sure that the information you seek can only be determined by probing for it. The information is always in fluid motion by allocation and deallocation of running processes, it could only be a snapshot of the current situation, and of course, for taking the snapshot, all processes would have to be suspended temporarily. So the information you would get after Windows scanning for a result and returning it to you would not be accurate or resilient, as the structure of the memory allocation could very well have changed by now.

like image 37
0xCAFEBABE Avatar answered Feb 28 '23 00:02

0xCAFEBABE