1.安装 valgrind

  yum install valgrind

2.测试用例

main.cpp

#include <iostream>

using namespace std;

struct StockInfo
{
int iMarket;
string sCode; StockInfo()
: iMarket(0)
{
}
}; int main()
{
StockInfo *pStockInfo = new StockInfo;
pStockInfo->iMarket = 1;
pStockInfo->sCode = "000001";
cout << "Market:" << pStockInfo->iMarket << "|" << "Code:" << pStockInfo->sCode << endl; //delete pStockInfo;
return 0;
}

makefile

TARGET=main

INC=
LIB_PATH=
LIB= CFLAGS:=-Wall -g -O0 -lrt -rdynamic -fPIC -Wl,-rpath=./ $(INC) $(LIB_PATH)
CPPFLAGS:=$(CFLAGS) SRC=$(shell echo *.cpp)
OBJ=$(patsubst %.cpp,%.o,$(SRC)) all: $(TARGET) $(TARGET): $(OBJ)
$(CXX) $^ $(CFLAGS) $(LIB) -o $@ clean:
rm -f $(OBJ)
rm -f $(TARGET)

make 编译生成可执行文件:

Linux 下用 valgrind 查找内存泄漏小例子-LMLPHP

3.使用 valgrind 检查内存泄漏:

  valgrind --tool=memcheck --leak-check=full ./main

Linux 下用 valgrind 查找内存泄漏小例子-LMLPHP

main.cpp第18行: 

  StockInfo *pStockInfo = new StockInfo;
new 的指针,没有释放,造成内存泄漏。
 
加上

  delete pStockInfo;
之后就没有内存泄漏了:
05-11 20:18