2.7 内存泄漏检测插件
  内存泄漏一直是C/C++代码中令人头疼的问题, 还好, CPPUTest 中提供了检测内存泄漏的插件, 使用这个插件, 可使我们的代码更加健壮.
  使用内存检测插件时, 测试代码 和 待测代码 在编译时都要引用.
  -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h
  makefile 修改如下:
# makefile for sample cpputest
CPPUTEST_HOME = /home/wangyubin/Downloads/cpputest-3.6
CC      := gcc
CFLAGS    := -g -Wall
CFLAGS  += -std=c99
CFLAGS  += -D CPPUTEST            # 编译测试文件时, 忽略sample.c的main函数, sample.c的代码中用了宏CPPUTEST
# CPPUTest 是C++写的, 所以用 g++ 来编译 测试文件
CPP     := g++
CPPFLAGS  := -g -Wall
CPPFLAGS  += -I$(CPPUTEST_HOME)/include
LDFLAGS := -L$(CPPUTEST_HOME)/lib -lCppUTest
# 内存泄露检测
MEMFLAGS = -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h
sample: sample.o
sample.o: sample.h sample.c
$(CC) -c -o sample.o sample.c $(CFLAGS) $(MEMFLAGS)
# 追加的测试程序编译
test: test.o sample.o
$(CPP) -o $@ test.o sample.o $(LDFLAGS)
test.o: sample.h test.c
$(CPP) -c -o test.o test.c $(CPPFLAGS)  $(MEMFLAGS)
.PHONY: clean
clean:
@echo "clean..."
rm -f test sample
rm -f sample.o test.o
  修改 sample.c 中的 init_student 函数, 构造一个内存泄漏的例子.
/* s->name = name, s->score = score */
void init_student(struct Student* s, char* name, int score)
{
char* name2 = NULL;
name2 = (char*) malloc(sizeof(char) * 80); /* 这里申请的内存, 后没有释放 */
strcpy(s->name, name2);
strcpy(s->name, name);
s->score = score;
}
  修改 test.c 追加一个测试 init_student 函数的测试用例
  TEST(sample, init_student)
  {
  struct Student *stu = NULL;
  stu = (struct Student*) malloc(sizeof(struct Student));
  char name[80] = {'t', 'e', 's', 't', ''};
  init_student(stu, name, 100);
  free(stu);
  }
  执行测试, 可以发现测试结果中提示 sample.c 72 行有内存泄漏风险,
  这一行正是 init_student 函数中用 malloc 申请内存的那一行.
$ make clean
clean...
rm -f test sample
rm -f sample.o test.o
$ make test
g++ -c -o test.o test.c -g -Wall -I/home/wangyubin/Downloads/cpputest-3.6/include  -include /home/wangyubin/Downloads/cpputest-3.6/include/CppUTest/MemoryLeakDetectorMallocMacros.h
gcc -c -o sample.o sample.c -g -Wall -std=c99 -D CPPUTEST             -include /home/wangyubin/Downloads/cpputest-3.6/include/CppUTest/MemoryLeakDetectorMallocMacros.h
g++ -o test test.o sample.o -L/home/wangyubin/Downloads/cpputest-3.6/lib -lCppUTest
$ ./test -v -n init_student
  TEST(sample, init_student)测试开始......
  测试结束......
  test.c:47: error: Failure in TEST(sample, init_student)
Memory leak(s) found.
Alloc num (4) Leak size: 80 Allocated at: sample.c and line: 72. Type: "malloc"
Memory: <0x120c5f0> Content: ""
Total number of leaks:  1
NOTE:
Memory leak reports about malloc and free can be caused by allocating using the cpputest version of malloc,
but deallocate using the standard free.
If this is the case, check whether your malloc/free replacements are working (#define malloc cpputest_malloc etc).
- 0 ms
Errors (1 failures, 3 tests, 1 ran, 0 checks, 0 ignored, 2 filtered out, 0 ms)