内存泄露

来源:互联网 发布:苹果mac电脑壁纸 编辑:程序博客网 时间:2024/04/20 09:07

在看趋势科技的面试题时候看到的,这个公司主要是服务器上后台开发,用的也是C++为多,所以会问这个问题吧。这个自己也没什么经验,毕竟内存对于我写的东西来说已经足够大了,虽然写过服务器后台程序,但是没写过那么复杂的东西。维基百科上的定义“A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system.”定义不难理解,就是堆上的内存,不用了但是没有释放掉。

Consequences:后果很严重。最简单的情况,如果程序需要在后台一直运行,或者是运行很长时间,随着时间的增长,那么泄露的内存可能很多,最终导致系统性能下降或者崩溃。

出现后的解决方法和预防措施:这个其实没找到最答案,自己总结的一点,以后
1. 如果代码简单,直接匹配的找new和delete就行了。
2. C++的智能指针。
3. 用一些代码的检测和debug工具:Typically, a memory leak occurs because dynamically allocated memory has become unreachable. The prevalence of memory leak bugs has led to the development of a number of debugging tools to detect unreachable memory. IBM Rational Purify, BoundsChecker, Valgrind, Insure++ and memwatch are some of the more popular memory debuggers for C and C++ programs.
4. 写代码的时候利用栈的特性,例如一些对象,可以在栈上也可以在堆上,那么最好写在栈上,写好构造函数,那么当退出这个对象的生存周期的时候,会自动调用析构函数来完成对象的析构。
5. 对于一些长期运行服务器程序,可以自己预先分配内存,自己写内存分配算法,(内存池)这样也减少了内存的申请和收回,对于程序的效率也可以有大大的提升。

参考:http://en.wikipedia.org/wiki/Memory_leak

原创粉丝点击