【发布时间】:2009-08-11 10:53:50
【问题描述】:
我想了解在以下情况下 GCC 运行时发生了什么。
我有一个 C++ 程序,它分配许多内存块,然后删除它们。令人费解的是,GCC 运行时没有将内存返回给操作系统。相反,它仍然由我的程序保留,我假设我想在不久的将来分配类似的内存块。
以下程序演示了会发生什么:
#include <iostream>
using namespace std;
void pause1()
{
cout << "press any key and enter to continue";
char ch;
cin >> ch;
}
void allocate(int size)
{
int **array = new int*[size];
for (int c = 0; c < size; c++) {
array[c] = new int;
}
cout << "after allocation of " << size << endl;
for (int c = 0; c < size; c++) {
delete array[c];
}
delete [] array;
}
int main() {
cout << "at start" << endl;
pause1();
int size = 1000000;
for (int i = 0; i < 3; i++) {
allocate(size);
cout << "after free" << endl;
pause1();
size *= 2;
}
return 0;
}
我通过运行“ps -e -o vsz,cmd”检查进程在每次暂停时(当它根本不应该持有任何内存时)所持有的内存量。
进程在每次暂停时持有的数量如下:
2648kb - 开始 18356kb - 在分配和释放 1,000,000 个整数之后 2780kb - 在分配和释放 2,000,000 个整数之后 65216kb - 分配和释放 4,000,000 个整数后我在 Fedora Core 6 上运行并使用 GCC 4.1.1。
【问题讨论】:
-
为什么会出现这个问题?它会导致内存不足吗?
-
问题是由于内存使用量高的情况下交换导致机器速度变慢;如果内存实际上已被应用程序释放,我想避免的事情。
标签: c++ memory gcc memory-management