我将在一个程序分配和使用内存时发生什么的例子来解释这一点.具体来说,这个程序:
#include
#include
#include
#include
int main(){
int *data, size, count, i;
printf( "fyi: your ints are %d bytes large\n", sizeof(int) );
printf( "Enter number of ints to malloc: " );
scanf( "%d", &size );
data = malloc( sizeof(int) * size );
if( !data ){
perror( "failed to malloc" );
exit( EXIT_FAILURE );
}
printf( "Enter number of ints to initialize: " );
scanf( "%d", &count );
for( i = 0; i < count; i++ ){
data[i] = 1337;
}
printf( "I'm going to hang out here until you hit " );
while( getchar() != '\n' );
while( getchar() != '\n' );
exit( EXIT_SUCCESS );
}
这是一个简单的程序,要求您分配多少个整数,分配它们,询问要初始化多少整数,然后初始化它们.对于我分配1250000个整数并初始化其中的500000个的运行:
$./a.out
fyi: your ints are 4 bytes large
Enter number of ints to malloc: 1250000
Enter number of ints to initialize: 500000
Top报告以下信息:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ SWAP CODE DATA COMMAND
11129 xxxxxxx 16 0 3628 408 336 S 0 0.0 0:00.00 3220 4 124 a.out
11129 xxxxxxx 16 0 8512 476 392 S 0 0.0 0:00.00 8036 4 5008 a.out
11129 xxxxxxx 15 0 8512 2432 396 S 0 0.0 0:00.00 6080 4 5008 a.out
相关资料为:
DATA CODE RES VIRT
before allocation: 124 4 408 3628
after 5MB allocation: 5008 4 476 8512
after 2MB initialization: 5008 4 2432 8512
在我malloc’d 5MB的数据后,VIRT和DATA都增加了约5MB,但RES没有.在我触摸了我分配的整数的2MB后,RES的确增加了,但DATA和VIRT保持不变.
VIRT是进程使用的虚拟内存的总量,包括共享和what is over-committed.DATA是不共享的虚拟内存量,而不是代码文本.即,它是进程的虚拟堆栈和堆. RES不是虚拟的:它是对该进程在该特定时间实际使用多少内存的测量.
所以在你的情况下,大的不等式CODE DATA< RES可能是进程包含的共享库.在我的例子(和你的)中,SHR代码数据更接近于RES. 希望这可以帮助.
与top和ps有很多的挥手和巫术.在线有很多文章(咆哮?),关于这些不符之处.例如this和this.