Home > Software engineering >  Dynamic allocation and pagination
Dynamic allocation and pagination

Time:09-16

I'm trying to monitor (with the system monitor) the total memory dynamically allocated by a snipped (for whatever reasons: I know, it sounds academic). Here's what I use (I know I'm not deallocating, and that the code is ugly).

#include <iostream>
#include <thread>
#include <cstdint>

using namespace std;

int main()
{               
    long long unsigned j = 0;
    while(true)
    {
        int * pt = new int32_t[250 * 1000 * 10]; //10MB
        static long long unsigned int m2GB = 200; //loop rounds needed to allocate 2GB
        j  ;
        if(j % 10 == 0) //100MB per 100MB
        {
            cout << (j*10) << "MB allocated" << endl;
            this_thread::sleep_for(100ms);
        }
        if(j >= m2GB)
            break;
    }

    cout << "Type sth to close" << endl;
    cin >> j; //blocking
}

Thing is... I don't even see a spike with this code, while, if I'm not mistaken, it should allocate up to 2GB of memory.

... what am I doing wrong ?

CodePudding user response:

Your code is not using the allocated memory. The compiler is going to notice that and will simply optimize the allocation away.

If you want to observe the memory being allocated use it in such a way that it is not trivial to perform the same action without the allocation. What exactly that means will depend on how good the compiler's optimizer is. It may be enough to zero-initialize the memory, or actual connection to input/output may be needed.

CodePudding user response:

Chris and @user17732522 are right: both compilers and OS's optimize allocation so unused memory isn't committed. THe following correction on the above code does the trick.

#include <iostream>
#include <thread>
#include <cstdint>

using namespace std;

void mishmash(int32_t* p, int size)
{
    int dummy;
    for(int i = 0; i < size; i  )
    {
        *p = 42;
        dummy = *p;
        p  ;
    }
}

int main()
{               
    long long unsigned j = 0;
    while(true)
    {
        static long long unsigned m10MB = 250 * 1000 * 10;
        int32_t * pt = new int32_t[m10MB]; //10MB
        mishmash(pt, m10MB);
        static long long unsigned int rounds2GB = 200; //loop rounds needed to allocate 2GB
        j  ;
        if(j % 10 == 0) //100MB per 100MB
        {
            cout << (j*10) << "MB allocated" << endl;
            this_thread::sleep_for(100ms);
        }
        if(j >= rounds2GB)
            break;
    }

    cout << "Type sth to close" << endl;
    cin >> j; //blocking
}   
  • Related