《Programming Applications For Microsoft Windows》中提到了如何使用Windows的虚拟内存,以及使用虚拟内存的优势。
但一直没有机会利用该技术实现内存池之类的东东。也就对该技术没什么实际体验。
昨天看到一篇文章《[原创]malloc&realloc [malloc和realloc以及堆与虚拟内存]》。作者列出了输入输出,但没有作过多的解释。
不知道作者的意图是否是要说明Windows下的c-runtime使用了该技术。
没机会实现内存池,而从c-runtime的实现的一些效果来管中窥豹, 也算稍稍实际体会了一下虚拟内存的知识吧……
稍稍修改一下作者的例子:
注意: 需要导入psapi 库。
如果是MSVC,可以在源代码中加入 #pragma comment(lib,"psapi.lib");
如果是GCC,除了在使用-l, 不知道有没有在源代码中导入库的方法么……
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <windows.h>
#include <psapi.h>
void Print(const char* format, ...)
{
va_list ap;
PROCESS_MEMORY_COUNTERS info;
va_start(ap,format);
vprintf(format,ap);
va_end(ap);
ZeroMemory(&info,sizeof(info));
GetProcessMemoryInfo(
GetCurrentProcess()
,&info
,sizeof(info));
printf("usage=%13u kb / virtual=%13u kb\n\n"
,(unsigned)(info.WorkingSetSize / 1024)
,(unsigned)(info.PagefileUsage / 1024) );
}
int main()
{
const size_t buf_size1 = 50*1024*1024;
const size_t buf_size2 = 150*1024*1024;
char* p = 0;
SYSTEM_INFO info;
GetSystemInfo(&info);
printf("PAGE SIZE = %u\n\n",(unsigned)info.dwPageSize);
Print("test1 begin\n");
p = (char*) malloc(buf_size1);
Print("malloc %u\n",buf_size1);
p = (char*) realloc(p, buf_size2);
Print("realloc to %u\n",buf_size2);
free(p);
Print("free\n");
Print("test2 begin\n");
p = (char*) malloc(buf_size1);
Print("malloc %u\n",buf_size1);
p[0] = 0;
Print("assign first %d\n",0);
p[buf_size1-1] = 0;
Print("assgin last %d\n",0);
p = (char*) realloc(p, buf_size2);
Print("realloc to %u\n",buf_size2);
free(p);
Print("free\n");
Print("test3 begin:\n");
p = (char*) calloc(buf_size1,1);
Print("calloc %u %u\n",buf_size1,1);
p = (char*) realloc(p,buf_size2);
Print("realloc to %u\n",buf_size2);
free(p);
Print("free\n");
return 0;
}
程序输出:
PAGE SIZE = 4096
test1 begin
usage= 844 kb / virtual= 248 kb
malloc 52428800
usage= 848 kb / virtual= 51552 kb
realloc to 157286400
usage= 52276 kb / virtual= 154156 kb
free
usage= 968 kb / virtual= 248 kb
test2 begin
usage= 968 kb / virtual= 248 kb
malloc 52428800
usage= 972 kb / virtual= 51552 kb
assign first 0
usage= 972 kb / virtual= 51552 kb
assgin last 0
usage= 980 kb / virtual= 51552 kb
realloc to 157286400
usage= 52276 kb / virtual= 154156 kb
free
usage= 968 kb / virtual= 248 kb
test3 begin:
usage= 968 kb / virtual= 248 kb
calloc 52428800 1
usage= 972 kb / virtual= 51552 kb
realloc to 157286400
usage= 52276 kb / virtual= 154156 kb
free
usage= 968 kb / virtual= 248 kb
Terminated with return code 0
Press any key to continue ...
分析:
编译器:gcc (GCC) 3.4.2 (mingw-special), Release默认
第1个测试和作者是差不多的。
malloc只是保留了50M内存,并没有提交。实际使用的内存只增加了1页。
而realloc后,可以看出保留了150M内存,
但是:
疑惑一:为什么前50M被提交了呢??
第2个测试是在malloc后,马上修改内存。
可以看出,修改p[0], 没有导致新的提交
但是:
疑惑二:为什么修改p[buf_size1-1],导致提交了2页?
第3个测试是使用calloc分配,照理说会清零。
但是
疑惑三:为什么只提交了1页?
runtime并没有清零, 而是留下未清零标志,等到提交后再清零?
posted on 2008-11-15 00:39 OwnWaterloo 阅读(3486)
评论(29) 编辑 收藏