【发布时间】:2009-08-14 17:38:10
【问题描述】:
这是一个简单的 windows d/tango 代码:
module d_test.d;
import tango.util.log.Trace;
import tango.core.Thread;
import tango.stdc.stdlib : malloc, free;
void main() {
Trace.formatln("Checking in...");
Thread.sleep(10);
int total_n = (100 * 1000 * 1000) / int.sizeof; // fill mem with 100MB of ints
int* armageddon = cast(int*)malloc(total_n * int.sizeof);
for(int i = 0; i < total_n; ++i) {
armageddon[i] = 5;
}
Trace.formatln("Checking in...");
Thread.sleep(10);
free(armageddon);
armageddon = null;
Trace.formatln("Checking in...");
Thread.sleep(10);
}
当我运行程序时,内存保持低~2MB,当我为指针分配一个 100MB 的数组时,内存使用量跳到~100MB,这很好。但是,在程序结束后,可用内存仍然(我正在查看任务管理器)为 100MB。
我认为可能是windows页面文件缓存什么的,所以我尝试了一个简单的C++程序:
#include <iostream>
#include <windows.h>
using namespace std;
int main() {
Cout << "Checking in..." <<< endl;
Sleep(10000);
int total_n = (100 * 1000 * 1000) / sizeof(int);
int* armageddon = (int*)malloc(total_n * sizeof(int));
for(int i = 0; i < total_n; ++i) {
armageddon[i] = 5;
}
Cout << "Checking in..." <<< endl;
Sleep(10000);
free(armageddon);
armageddon = NULL;
Cout << "Checking in..." <<< endl;
Sleep(10000);
return 0;
}
我已经用 g++ 编译了它,一切似乎都正常工作。程序启动时 - 内存使用 ~900kb,分配后 ~100MB,释放后 ~1,2MB...
那么,我做错了什么还是这是一个错误?
【问题讨论】:
-
malloc 和 free 只是 C 调用的说唱歌手。我不知道为什么结果会不同。
-
哟哟! // 我的名字是 malloc,我是一个糟糕的说唱歌手。 // 把你所有的记忆都给我,我会把它扔进垃圾箱里