valgrind使用指南
一、内存泄露检测
文件test_valgrind.cpp
#include <iostream>
int main() {
int* a = NULL;
a = new int[10];
return 0;
}
g++ -g test_valgrind.cpp
valgrind --leak-check=yes ./a.out
输出如下:
从上图可以看出,有40bytes的内存尚未释放,问题代码在该文件的第5行。
使用技巧:用valgrind时, 强烈建议加上参数: --error-limit=no, 不加--error-limit=no参数时,超过一定警告数量后,就不再打warning信息了,要让所有warning都打出来,要用!!
二、线程错误检测
文件test_helgrind.cpp:
#include <pthread.h>
int var = 0;
void* child_fn ( void* arg ) {
var++; /* Unprotected relative to parent */ /* this is line 6 */
return NULL;
}
int main ( void ) {
pthread_t child;
pthread_create(&child, NULL, child_fn, NULL);
var++; /* Unprotected relative to child */ /* this is line 13 */
pthread_join(child, NULL);
return 0;
}
编译: g++ -g test_helgrind.cpp -lpthread
运行helgrind: valgrind --tool=helgrind ./a.out
结果如下:代码提示主线程和子线程都在写var.