typedef struct node{
unsigned int v;
struct node* next;
}Node;
When allocating at once, the memory used was around 4GB
Node* X= (Node*)malloc(sizeof(Node)*((long)1<<28));
and when allocating each Node dynamically the memory used was almost doubled to around 8GB
temp = (Node*)malloc(sizeof(Node)); //This is run 1<<28 times
Ideally both should take the same amount of memory if everything else stays the same. But the fact that it doesn't happen says that there is an overhead of some bookkeeping in the 2nd approach.
Please explain in detail why this is happening. I would appreciate fine details like the data structures used for bookkeeping using which we can calculate the expected usage of memory.
P.S I am using a 64-bit machine (8 byte pointer) and gcc 4.4.7 compiler.
I was accessing all of the allocated Nodes, so Virtual Memory and RAM used was the same. There is no smart allocation going on.
I will be happy to give out any details about my system if someone can find the time to give a detailed answer about everything happening under the hood.