C++ new memory allocation fragmentation
- by tamulj
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.