After running the following code:
#include <stdio.h>
class Nil
{
};
int main()
{
Nil* A[20];
char* B[20];
for (int i=0;i!=20;i++)
{
A[i]=new Nil;
}
for (int i=0;i!=19;i++)
{
printf("A:%i\n",((int)A[i+1])-((int)A[i]));
}
printf("------------------------------------\n",5);
for (int i=0;i!=20;i++)
{
B[i]=new char;
}
for (int i=0;i!=19;i++)
{
printf("B:%i\n",((int)B[i+1])-((int)B[i]));
}
getchar();
}
OUTPUT:
A:7112
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
A:64
------------------------------------
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
B:64
why is the allocation size always 64?
C++ memory manager handles allocations as it pleases. The gaps are larger than the objects because the manager needs additional information to know what memory is taken and what is free. All the chunks have the same size thanks to memory padding, for greater efficiency. Notice that should you try allocating large objects, the gaps would widen, most likely by multiples of 64. The gaps between allocated objects are the same, because you allocated them in a sequence – stacking new objects is the most simple allocation strategy. Notice that if the allocations weren’t in sequence or if there were ‘holes’ of free memory, the gaps would not be so even.
The important thing to remember is that all of this is implementation and platform dependent and should not be relied on.