I have the following piece of sample code allocating 1D array:
#define C 3
int main() {
int *a;
long long N = 1000000000, i;
a = (int*)malloc(sizeof(int) * N * C);
for (i = 0; i < N * C; i++)
a[i] = i / 2;
printf("%d\n", a[N*C - 1]);
return 0;
}
The above code takes exactly 12 GB of data in memory.
Note that sizeof(int) == 4 and sizeof(int*) == 8.
Now, if I implement a dynamic 2D array using the following code:
#define C 3
int main() {
int **a;
long long N = 1000000000, i;
a = (int**)malloc(sizeof(int*) * N);
for (i = 0; i < N; i++)
a[i] = (int*)malloc(sizeof(int) * C);
for (i = 0; i < N; i++)
for (j = 0; j < C; j++)
a[i][j] = i;
printf("%d\n", a[N-1][C-1]);
return 0;
}
The above code strangely takes around 38 GB of memory (whilst it should have taken 12GB + 8GB (for array of pointers) = 20 GB.
Strangely enough, in the second sample code, if I increase the value of C to 4, 5, 6, the memory consumed is exactly the same (38 GB), while for C=7 and C=8 the memory consumed is 54 GB, and for C=16 the memory consumed is 86 GB. This doesn't fit any math I could figure out. Can anyone help me out with this?