使用gdb调试,可以发现一些我们理解错误的逻辑问题,一般情况下我都是使用gdb进行调试的。
但有时我们的应用程序很大,我们不知道哪里出的问题,即gdb调试不知道在哪里打断点(当然也可以单步或者自己定几个断点),这个时候就需要有别的方法来找到出错的大概位置。
假设我们在程序中,对为初始化的指针赋值。或者对已经释放的内存进行了使用,很容易导致段错误。
这里我以一个简单的例子为例来说明。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
void func(int *p )
{
*p = 666;
}
int main(void)
{
int *p = NULL;
int val = 333;
printf("val = %d \n",val);
func(&val);
printf("val = %d \n",val);
/*
* 对NULL地址赋值
*/
func(p);
printf("val = %d \n",*p);
return 0;
}
正常情况下,应用程序访问了非法地址,就会导致段错误。
<