1.安装 valgrind
yum install valgrind
2.测试用例
main.cpp
#includeusing 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=mainINC=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 编译生成可执行文件:
3.使用 valgrind 检查内存泄漏:
valgrind --tool=memcheck --leak-check=full ./main
main.cpp第18行:
StockInfo *pStockInfo = new StockInfo;
new 的指针,没有释放,造成内存泄漏。
加上
delete pStockInfo;
之后就没有内存泄漏了:
valgrind 用法详见: