I would like to understand why data dynamically allocated called multiple times uses so much memory than the one directly specified on code or allocated with a single call of malloc
.
Examples
As example, I made the following two codes, in C:
test1.c: int x is allocated with malloc
int main (void)
{
int *x;
int i, n=1048576; //n=1024*1024;
printf("size = %lu\n", n* sizeof(int));
for(i=0; i<n; i++)
{
x = malloc(sizeof(int));
*x=i;
}
printf("Look at top and then press something to finish.");fflush(stdout);
getc(stdin);
return 0;
}
I did not use free here to keep it simple. When the program is waiting for interaction, I look at the top function in another terminal, and it shows me this:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1384 root 20 0 41300 34076 1300 S 0.0 3.3 0:00.47 test1
test2.c: int x is not allocated dynamically
int main (void)
{
int x[1048576]; //x[1024*1024]
int i, n=1048576;
printf("size = %lu\n", n* sizeof(int));
for(i=0; i<n; i++)
{
x[i]=i;
}
printf("Look at top and then press something to finish.");fflush(stdout);
getc(stdin);
return 0;
}
And top shows me:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1352 root 20 0 12404 5500 1304 S 0.0 0.5 0:00.05 test2
I also did a third code, which has the same result that test2, where I used:
x = malloc(n*sizeof(int));
for(i=0; i<n; i++)
{
x[i]=i;
}
Why so much difference on the memory use of the processes? That is because malloc request new memory pages and are there memory being wasted? Or malloc
allocates more memory?
test1 uses 3.3% of the total memory and test2 uses 0.5%.
Environment:
I am executing those tests on Centos 5 64 bits inside docker.
Memory on the virtual environment:
$ free -m
total used free shared buff/cache available
Mem: 995 98 845 3 51 808
Swap: 1162 194 967