I've been running into a problem trying to show the amount of memory used up by dynamically allocated arrays using the linux tool top
through a system()
call in my program.
#include <stdio.h>
#include <stdlib.h>
int main() {
int Array_Length = getpagesize();
int pid = getpid();
char top_call[22];
sprintf(top_call, "top -b -n1 -p %d", pid);
int *Array1 = malloc(Array_Length * sizeof(int));
int *Array2 = malloc(Array_Length * sizeof(int));
system(top_call);
int i;
for(i = 0; i < Array_Length; i++) {
Array1[i] = 1;
Array2[i] = 1;
}
system(top_call);
return 0;
}
First system(top_call)
results were as I expected:
top - 18:30:01 up 5:05, 2 users, load average: 0.00, 0.01, 0.04
Tasks: 1 total, 0 running, 0 sleeping, 0 stopped, 0 zombie
Cpu(s): 0.3%us, 0.1%sy, 0.0%ni, 99.5%id, 0.1%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 249852k total, 236660k used, 13192k free, 66180k buffers
Swap: 407548k total, 128k used, 407420k free, 72952k cached
PID VIRT RES SHR %MEM SWAP CODE DATA
2000 10280 564 464 0.2 9716 8 8512
Since malloc()
uses lazy allocation, after the second system(top_call)
I was expecting the memory usage to increase since the arrays have now been accessed. However, the results after the second call show the same amount of memory usage from my process:
top - 18:41:22 up 5:16, 2 users, load average: 0.00, 0.01, 0.04
Tasks: 1 total, 0 running, 0 sleeping, 0 stopped, 0 zombie
Cpu(s): 0.3%us, 0.1%sy, 0.0%ni, 99.5%id, 0.1%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 249852k total, 236052k used, 13800k free, 66236k buffers
Swap: 407548k total, 128k used, 407420k free, 72948k cached
PID VIRT RES SHR %MEM SWAP CODE DATA
2000 10280 564 464 0.2 9716 8 8512
Can anyone explain why my arrays aren't using up any memory?
Apologies if the formatting isn't that great.