Linux程序设计(21)第十章:调试:常用调试技巧,gdb,断言assert,valgrind

1. 常用调试技巧

程序调试的5个步骤:

测试:找出错误
固化:让错误可重现
定位:定位错误原因,代码处
修改:修改代码
验证:确定是否修改成功

2. gdb

通俗易懂说GDB调试(一)
https://blog.csdn.net/lqy971966/article/details/88963635
通俗易懂说GDB调试(二)
https://blog.csdn.net/lqy971966/article/details/102812016
通俗易懂说GDB调试(三)总结
https://blog.csdn.net/lqy971966/article/details/103118094

3. 断言 assert

void assert(int expression)

3.1 功能:

assert宏对表达式进行求值,如果结果非零,
它就往标准错误写一些诊断信息,然后调用abort函数结束程序的运行。

3.2 assert 是一个宏,不是函数

3.3 例子:

测试某个程序是否成立,如果不成立则停止程序的运行。

如: assert(NULL != pcName);

断言不能含有业务逻辑,只能有逻辑表达式

3.4 debug release版本区别

debug版本会执行断言;release版本不会执行断言
因为,debug版本含有调试信息,不会对程序进行优化;assert相应的宏会被执行
release版本中不含有调试信息,会对程序进行优化,assert相应的宏不会被执行

3.5 -DNDEBUG 关闭断言 例子

#include<stdio.h>
#include<math.h>
#include<assert.h>
#include<stdlib.h>

double sqrt(double x)
{
	assert(x >= 0.0);
	return sqrt(x);
}

int main()
{
	printf("sqrt/2 = %g\n",sqrt(2.0));
	printf("sqrt/-2 = %g\n",sqrt(-2.0));
	return 0;
}

结果:

[root@localhost linux-]# gcc assert.c -lm
[root@localhost linux-]# ./a.out 
sqrt/2 = 1.41421
a.out: assert.c:8: sqrt: Assertion `x >= 0.0' failed.
Aborted (core dumped)
[root@localhost linux-]# 
[root@localhost linux-]# gcc assert.c -lm -DNDEBUG
[root@localhost linux-]# ./a.out 
sqrt/2 = 1.41421
Segmentation fault (core dumped)
[root@localhost linux-]#

4. 内存调试 valgrind

linux 开源内存泄露检测工具: valgrind
https://blog.csdn.net/lqy971966/article/details/110563576

Guess you like

Origin blog.csdn.net/lqy971966/article/details/120976619