C 奇怪的行为:指针数与专用字节数
我正在32位Windows(Windows XP)上编写服务器组件。我在代码中有很多分配、取消分配和重新分配。我让这个组件运行了几个小时,然后把它关掉了。我发现很多内存(私有字节)仍然分配给进程(我使用SysInternals进程资源管理器监视私有字节) 代码中肯定没有内存泄漏。因此,我进一步研究并提出了这段代码,它再现了完全相同的行为C 奇怪的行为:指针数与专用字节数,c,windows,pointers,memory,memory-management,C,Windows,Pointers,Memory,Memory Management,我正在32位Windows(Windows XP)上编写服务器组件。我在代码中有很多分配、取消分配和重新分配。我让这个组件运行了几个小时,然后把它关掉了。我发现很多内存(私有字节)仍然分配给进程(我使用SysInternals进程资源管理器监视私有字节) 代码中肯定没有内存泄漏。因此,我进一步研究并提出了这段代码,它再现了完全相同的行为 #define NUMBER_OF_POINTERS 1000 int _tmain(int argc, _TCHAR* argv[]) { char
#define NUMBER_OF_POINTERS 1000
int _tmain(int argc, _TCHAR* argv[])
{
char* ptr[NUMBER_OF_POINTERS] = {} ;
int len[NUMBER_OF_POINTERS]={};
printf("\nCheck private bytes now and press a key to go on realloc");
_getch();
printf("\nRandomly allocating/reallocating memory. Press x to stop...");
while(1)
{
int random_kilobytes = rand() % 7 + 1;
int randomindex = rand()%NUMBER_OF_POINTERS;
int size2increase = random_kilobytes*1024;
assert (len[randomindex]+size2increase > 0);
char* reallocated = (char*) realloc(ptr[randomindex], len[randomindex]+size2increase);
if (reallocated)
{
ptr[randomindex] = reallocated;
len[randomindex] += size2increase;
}
if ((_kbhit()) && (_getch()=='x'))
break;
}
printf("\nPress a key to free allocations");
_getch();
for (int i=0; i<NUMBER_OF_POINTERS; i++)
free(ptr[i]);
int _heapmin_ret = _heapmin();
printf("\n_heapmin returned %d", _heapmin_ret);
printf("\nCheck private bytes now and press a key to exit");
_getch();
return 0;
}
定义指针的数量1000
int _tmain(int argc,_TCHAR*argv[]
{
char*ptr[指针的数量]={};
int len[指针的数量]={};
printf(“\n现在检查私有字节,然后按键进入realloc”);
_getch();
printf(“\n随机分配/重新分配内存。按x停止…”);
而(1)
{
int random_kilobytes=rand()%7+1;
int randomindex=rand()%u个指针;
int SIZE2GREASE=随机_千字节*1024;
断言(len[randomindex]+Size2Engress>0);
char*重新分配=(char*)realloc(ptr[randomindex],len[randomindex]+大小增加);
如果(重新分配)
{
ptr[randomindex]=重新分配;
len[randomindex]+=尺寸2增加;
}
如果((_-kbhit())&(_-getch()='x'))
打破
}
printf(“\n按一个键可自由分配”);
_getch();
对于(int i=0;iYou正在查看一个统计数据,该统计数据表示进程使用了多少虚拟内存。这只是一个数字,与您使用的物理内存量无关。释放分配不会减少数量,释放的地址空间块只会添加到空闲块列表中。供将来的分配重新使用。要使数字缩小,需要一个令人高兴且不太可能的巧合,即整个地址空间范围都没有使用。最好不要再盯着那些意义不大的数字看。1 GB的虚拟机没有问题。这可能会有所帮助。这些值都不是可执行文件实际使用内存量的可靠指标,也都不适合调试内存泄漏