搞定段错误!

来源:互联网 发布:linux ibus 安装 编辑:程序博客网 时间:2024/05/22 03:17

  原帖:http://www.lupaworld.com/333723/viewspace-127256.html

 

自己在学习写一个linux下的ls命令时,编译时没有错误但调试时总是有段错误,
让我很是郁闷,l像我这样的inux的菜鸟便开始了据说linux下很难的调试!
         1.利用gdb逐步查找段错误:
这种方法也是被大众所熟知并广泛采用的方法,首先我们需要一个带有调试信息的可执行程序,所以我们加上“-g -rdynamic"的参数进行编译,然后用gdb调试运行这个新编译的程序,具体步骤如下::
[neilhhw@localhost LinuxC]$ gdb ./my_ls
GNU gdb Fedora (6.8-1.fc9)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
(gdb) r
Starting program: /home/neilhhw/LinuxC/my_ls

Program received signal SIGSEGV, Segmentation fault.
0x00b6d6b3 in strlen () from /lib/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc.i686
(gdb) next
Single stepping until exit from function strlen,
which has no line number information.

Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb) q

我看不到什么有用的信息!
故,上网google一下:
在gdb下进行stack调试!具体如下:
GNU gdb Fedora (6.8-1.fc9)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
(gdb) r
Starting program: /home/neilhhw/LinuxC/my_ls

Program received signal SIGSEGV, Segmentation fault.
0x00b6d6b3 in strlen () from /lib/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc.i686
(gdb) bt
#0  0x00b6d6b3 in strlen () from /lib/libc.so.6
#1  0x08048d26 in displayDir (flagParam=0, path=0xbf800b9b "./") at my_ls.c:252
#2  0x080491cf in main (argc=1, argv=0xbf801c54) at my_ls.c:357
(gdb) q
The program is running.  Exit anyway? (y or n) y
[neilhhw@localhost LinuxC]$
哈哈,看到了,在252行!
故跳到这一行:
while((ptr=readdir(dir)!=NULL))    /*逻辑错误!*/
    {
        if(gMaxLen<strlen(ptr->d_name))
            gMaxLen=strlen(ptr->d_name);
        count++;
    }

原来是ptr=readdir(dir)!=NULL错误!
运算时先判断后赋值!造成ptr引用d_name有误:
改下就OK啦!

while((ptr=readdir(dir)!)=NULL)    /*逻辑错误!*/
    {
        if(gMaxLen<strlen(ptr->d_name))
            gMaxLen=strlen(ptr->d_name);
        count++;
    }

运行成功!
本以为linux下调试会很难!不过就是这么简单好用,而且还简洁啊!
不过,指针真的要好好用,不然就会让我调了一下午啊!
好好学习,天天向上!