Head First C学习之安装valgrind和使用
2016-03-30 本文已影响220人
燚随风
Head Frist C:302页中用到了Valgrind工具,
关于valgrind
valgrind
是一个通过伪造malloc()
可以监控分配在堆的数据。
当程序想分配堆上的存储器时,valgrind
将会拦截你对malloc()
和free()
的调用,然后允许自己的malloc()
和free()
,valgrind
的malloc()
会记录调用他的是那一段代码,和分配了那一段存储器。
程序结束时,valgrind
回汇报堆上有哪些数据,并告诉你这些数据是哪段代码创建的。
安装valgrind
#curl -O http://valgrind.org/downloads/valgrind-3.11.0.tar.bz2
#tar -xjvf valgrind-3.11.0.tar.bz2
cd valgrind-3.11.0
#./configure
#make
#sudo make install
但是在make的过程中出现如下错误
#make[2]: *** No rule to make target `/usr/include/mach/mach_vm.defs', needed by `m_mach/mach_vmUser.c'. Stop.
#make[1]: *** [install-recursive] Error 1
#make: *** [install] Error 2
需要安装命令行工具脚本如下
#xcode-select --install
因为Mac是64位,所以需要将./configure改成如下脚本
#./configure --disable-tls --enable-only64bit --build=amd64-darwin
#make
#sudo make install
使用valgrind
调试代码(可疑人物识别专家系统(SPIES)):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
char *question;
struct node *no;
struct node *yes;
}node;
int yes_no(char *question)
{
char answer[3];
printf("%s?(y/n):",question);
fgets(answer,3,stdin);
return answer[0] == 'y';
}
node * create(char *question)
{
node *n = malloc(sizeof(node));
n->question = strdup(question);
n->no = NULL;
n->yes= NULL;
return n;
}
void release(node *n)
{
if (n){
if(n->no)
release(n->no);
if(n->yes)
release(n->yes);
if(n->question)
free(n->question);
free(n);
}
}
int main()
{
char question[80];
char suspect[20];//犯罪嫌疑人
node *start_node = create("Does suspect have a mustache");
start_node->no = create("Loretta Barnsworth");
start_node->yes = create("Vinny the Spoon");
node * current;
do{
current = start_node;
while(1){
if(yes_no(current->question)){
if(current->yes){
current = current->yes;
}else{
printf("SUSPECT IDENTIFIED\n");
break;
}
}else if(current->no){
current = current->no;
}else{
//
printf("Who 's the suspect?\n ");
fgets(suspect,20,stdin);
node *yes_node = create(suspect);
current->yes = yes_node;
//
node *no_node = create(current->question);
current->no = no_node;
//
printf("Give me a question that is True for %s but not %s? ",suspect,current->question);
fgets(question,80,stdin);
current->question = strdup(question);
break;
}
}
}while(yes_no("Run again"));
release(start_node);
return 0;
}
使用valgrind运行代码欠,余姚添加调试信息,-g
;
#gcc -g spies.c -o spies
#valgrind --leak-check=full ./spies
valgrind参考资料:
Mac下valgrind的安装和使用
Unix下C程序内存泄漏检测工具Valgrind安装与使用