Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ new memory allocation fragmentation

I was trying to look at the behavior of the new allocator and why it doesn't place data contiguously.

My code:

struct ci {
    char c;
    int i;
}

template <typename T>
void memTest()
{
    T * pLast = new T();
    for(int i = 0; i < 20; ++i) {
         T * pNew = new T();
         cout << (pNew - pLast) << " ";
         pLast = pNew;
    }
}

So I ran this with char, int, ci. Most allocations were a fixed length from the last, sometimes there were odd jumps from one available block to another.

sizeof(char) : 1
Average Jump: 64 bytes

sizeof(int): 4
Average Jump: 16

sizeof(ci): 8 (int has to be placed on a 4 byte align)
Average Jump: 9

Can anyone explain why the allocator is fragmenting memory like this? Also why is the jump for char so much larger then ints and a structure that contains both an int and char.

like image 655
Jason T. Avatar asked Nov 29 '22 18:11

Jason T.


1 Answers

There are two issues:

  • most allocators store some additional data prior to the start of the block (typically block size and a couple of pointers)

  • there are usually alignment requirements - modern operating systems typically allocate to at least an 8 byte boundary.

So you'll nearly always get some kind of gap between successive allocations.

Of course you should never rely on any specific behaviour for something like this, where the implementation is free to do as it pleases.

like image 99
Paul R Avatar answered Dec 05 '22 06:12

Paul R