【C++】常见的内存泄漏及解决方法

之所以撰写这篇文章是由于前段时间花费了非常大的精力在已经成熟的代码上再去处理memory leak问题。写此的目的是希望我们应该养成良好的编码习惯,尽可能的避免这种问题,由于当你对着一大片的代码再去处理此类的问题,此时无疑添加了解决的成本和难度。准确的说属于补救措施了。 一. 什么是内存泄漏(memory leak)? 指因为疏忽或错误造成程序未能释放已经不再使用的内存的情况。内存泄漏并不是指内存在物理上的消失,而是分配某段内存后,因为设计错误,失去了对该段内存的控制,因而造成了内存的浪费。 A memory leak is a particular type of unintentional memory consumption by a computer program where the program fails to release memory when no longer needed. This condition is normally the result of a bug in a program that prevents it from freeing up memory that it no longer needs.This term has the potential to be confusing, since memory is not physically lost from the computer. Rather, memory is allocated to a program, and that program subsequently loses the ability to access it due to program logic flaws.

三.解决方法:

1.良好的编程习惯

2.当在堆上申请了空间,一定要记得去收到释放

3.使用C++的智能指针

4.避免产生死锁的情况

5.打开的文件描述符一定要去关闭

6.利用一些第三方工具,去检测内存泄漏

经验分享 程序员 微信小程序 职场和发展