我正在 Linux(Fedora 10 和 CentOS 5)中使用 gcc 4.3.2 并使用 STL 容器实现我自己的图形库,然后我发现了一些内存问题。当我构建图表时,我使用了大量内存来查看top或其他内存使用工具。我确定我正在释放该内存(我一次又一次地检查了代码,并使用 valgrind 来检查内存泄漏),但内存仍在使用中(我可以在top or 猫 /proc/meminfo)并且当我再次创建图表时,它不会增加内存使用量,显然是重用了分配的内存。
经过几天的调试,我创建了一个非常简单的代码,但也有同样的问题。
#include <iostream>
#include <list>
// Object that occupies 128KB.
// Data is not important.
class MyObject
{
public:
int * a;
int * b;
int * c;
int * d;
MyObject( )
{
a = new int[ 8192 ];
b = new int[ 8192 ];
c = new int[ 8192 ];
d = new int[ 8192 ];
}
MyObject( const MyObject & m )
{
a = new int[ 8192 ];
b = new int[ 8192 ];
c = new int[ 8192 ];
d = new int[ 8192 ];
}
~MyObject( )
{
delete [] a;
delete [] b;
delete [] c;
delete [] d;
}
void operator=( const MyObject &m )
{
//Do nothing.
}
};
typedef std::list< MyObject > list_t;
#define MB_TO_ALLOC 1000 // Size in MB that the program must alloc.
#define SLEEP_TIME 5 // Time in seconds that the program must wait until go to another step.
// It's used to give sufficient time for tools update the memory usage
int main( )
{
std::cout << "Alloc..." << std::endl;
list_t * list = new list_t( );
// Number of objects for alloc MB_TO_ALLOC amount of memory
int nObjects = MB_TO_ALLOC * 1024 / 128;
for( int i = 0; i < nObjects; ++i )
list->push_back( MyObject( ) );
std::cout << SLEEP_TIME << "s to Dealloc..." << std::endl;
// Wait some time for a tool (like top) to update the memory usage
sleep( SLEEP_TIME );
std::cout << "Dealloc..." << std::endl;
delete list;
std::cout << SLEEP_TIME << "s to Alloc..." << std::endl;
// Wait some time for a tool (like top) to update the memory usage
sleep( SLEEP_TIME );
//Repeats the procedure for evaluating the reuse of memory
std::cout << "Alloc..." << std::endl;
list = new list_t( );
for( int i = 0; i < nObjects; ++i )
list->push_back( MyObject( ) );
std::cout << SLEEP_TIME << "s to Dealloc..." << std::endl;
sleep( SLEEP_TIME );
delete list;
}
我尝试使用简单数组或我自己的列表类,但在这些情况下,内存会正常释放。
有谁知道发生了什么事吗?如何防止这段内存被“保留”?
Thanks!
--
布鲁诺·卡波尼
除了 STL 容器之外,可能是 libc 本身这样做(new/delete - malloc/free 实现)。用户空间库可以自由保留内存以供以后重用。分配/解除分配是一项昂贵的操作(就时钟周期而言),因此许多实现都试图避免这种情况。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)