C++内存泄露问题

来源:互联网 发布:美国先锋集团 知乎 编辑:程序博客网 时间:2024/05/17 03:24

以下记录一下以前解决内存泄露问题的一些经历:

1、首先用valgrind工具进行检查(这个工具不能检查出所有问题):
(1)pthread_create引起的一个内存泄露
用valgrind –tool=memcheck –leak-check=full –undef-value-errors=yes ./connect_svr进行内存泄露检查时,提示:

624 bytes in 1 blocks are possibly lost in loss record 43 of 43
==567== at 0x4C2B974: calloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==567== by 0x4011DE4: _dl_allocate_tls (in /usr/lib64/ld-2.17.so)
==567== by 0x4E3D960: pthread_create@@GLIBC_2.2.5 (in /usr/lib64/libpthread-2.17.so)
==567== by 0x4A7E69: CLogger::Init(unsigned int, unsigned int, unsigned short) (Log.cpp:66)
==567== by 0x48E051: main (connect_route.cpp:75)

原因:
线程的分离状态决定一个线程以什么样的方式来终止自己。线程的默认属性是非分离状态,这种情况下,原有的线程等待创建的线程结束。只有当pthread_join()函数返回时,创建的线程才算终止,才能释放自己占用的系统资源。而分离线程不是这样子的,它没有被其他的线程所等待,自己运行结束了,线程也就终止了,马上释放系统资源。程序员应该根据自己的需要,选择适当的分离状态。

解决方法:
a.使用pthread_join()函数回收相关内存区域。
  pthread_t tid;
  void* state;
  pthread_create(&tid, NULL, test, NULL);
  pthread_join(tid, &state);

b.可以调用 pthread_detach() 函数分离线程。
  pthread_t tid;
  pthread_create(&tid, NULL, test, NULL);
  pthread_detach(tid);
  
  当然,也可以在 thread function 中调用。
  void* test(void* arg)
  {
  …..
  pthread_detach(pthread_self());
  return NULL;
  }
  
  c.使用线程属性。
  pthread_attr_t attr;
  pthread_t tid;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  pthread_create(&tid, &attr, test, NULL);
  sleep(3);//等待线程结束
  pthread_attr_destroy(&attr);
  根据实际需要,任选其一即可。

接下来还发现两个地方:
2、 new []操作没有写delete[]
char* szContent = new char[HTTP_RESPONSE_HTML_MAX];
snprintf(szContent, HTTP_RESPONSE_HTML_MAX, HTTP_RESPONSE_HTML, strContent.length(), strContent.c_str());

忘记写:
delete[] szContent;

3、单例类中未在析构函数中释放内存

CCRHttpConnMgr::~CCRHttpConnMgr() {
// TODO Auto-generated destructor stub
if(NULL != m_pInstance){
delete m_pInstance;
}
}

0 0
原创粉丝点击