在linux上用valgrind检查代码是否有内存泄漏时发现有5块资源申请没有释放:
命令格式: valgrind --tool=memcheck --leak-check=full --show-reachable=yes ./a.out
==27676== 5,160 bytes in 5 blocks are definitely lost in loss record 1 of 1
==27676== at 0x4C31556: operator new(unsigned long) (vg_replace_malloc.c:344)
==27676== by 0x417382: CLog::CLog() (c_log.cpp:16)
==27676== by 0x427DF5: GlobalInstance::GlobalInstance() (gameserver.cpp:265)
==27676== by 0x4276AE: main (gameserver.cpp:62)
==27676==
==27676== LEAK SUMMARY:
==27676== definitely lost: 5,160 bytes in 5 blocks
==27676== indirectly lost: 0 bytes in 0 blocks
==27676== possibly lost: 0 bytes in 0 blocks
==27676== still reachable: 0 bytes in 0 blocks
==27676== suppressed: 0 bytes in 0 blocks
这没有释放的5块资源根据valgrind显示的申请资源的堆栈信息和大小可以确定是list的10个预分配buff只释放了5个:
typedef struct
{
char buff[MAX_LOG_CONTENT];
int remain; //0 保留 1 用完释放
int level; //日志级别 0 1 2
}log_buff,*lplog_buff;
//一个log_buff 正好1032字节 * 5 = 5160
申请:
lplog_buff temp;
for(int i = 0; i < m_remainCount; i++) //m_remainCount = 10
{
temp = new log_buff;
temp->remain = 0;
m_freeList.push_back_no_signal(temp);
}
释放:
T temp;
cout<<"size: "<<size()<<endl; //这里输出10
for(int i = 0; i < size(); i++) //size: return std::list.size()
{
temp = m_list.front();
m_list.pop_front();
delete temp;
}
我先是肉眼观察如上释放地方的代码,认为没问题,就想是不是其他地方有pop然后没释放,但是没有,所以再怎么觉得没问题也需要打印数据看看:
释放:
T temp;
cout<<"size: "<<size()<<endl; //这里输出10
for(int i = 0; i < size(); i++) //size: return std::list.size()
{
cout<<"delete i: "<<i<<endl; //输出delete第几个元素
temp = m_list.front();
m_list.pop_front();
delete temp;
}
cout<<"delete over"<<endl; //确保析构执行完了的 之前还怀疑析构函数执行一半罢工了 呵呵
输出:
size: 10
delete i: 0
delete i: 1
delete i: 2
delete i: 3
delete i: 4
delete over
恍然大悟,"我是傻逼",循环执行5次就退出了, 因为判断语句用的 i < size(), 而在循环里我每delete一个元素就pop一个,当i=5的时候 size() == 5,循环就退出了。