fwrite的用法, 想必大家肯定很熟悉了。 但是, 很多人在调用fopen后, 不定返回的fp进行非空判断, 恕我直言, 确实有点小流氓。 实际上,在linux开发中, 受权限影响, 很多时候调用fopen会失败, 返回NULL. 在本文中, 我们来看看, 万一产生了core, 该如下定位。

         实际上, 对于gdb调试core, 我们已经比较熟悉了, 现在来强化一下, 如下:

[taoge@localhost test]$ ls
test.c
[taoge@localhost test]$ cat test.c -n
     1  #include <stdio.h>
     2
     3  int main()
     4  {
     5          FILE *fp = NULL;
     6          int a = 1;
     7          int b = 2;
     8          int c = a + b;
     9
    10          fwrite("abc", sizeof("abc"), 1, fp);
    11
    12          return 0;
    13  }
[taoge@localhost test]$ gcc -g test.c 
[taoge@localhost test]$ ls
a.out  test.c
[taoge@localhost test]$ ./a.out 
Segmentation fault (core dumped)
[taoge@localhost test]$ ls
a.out  core.3355  test.c
[taoge@localhost test]$ 
[taoge@localhost test]$ 
[taoge@localhost test]$ 
[taoge@localhost test]$ gdb a.out core.3355 
GNU gdb (GDB) Red Hat Enterprise Linux (7.1-29.el6)
Copyright (C) 2010 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 "i686-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/taoge/test/a.out...done.
[New Thread 3355]
Missing separate debuginfo for 
Try: yum --disablerepo='*' --enablerepo='*-debuginfo' install /usr/lib/debug/.build-id/74/d23352fd770753e375bd0caecf375bd77bded5
Reading symbols from /lib/libc.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib/ld-linux.so.2
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0  0x008de17c in fwrite () from /lib/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.7.el6.i686
(gdb) 
(gdb) 
(gdb) 
(gdb) bt
#0  0x008de17c in fwrite () from /lib/libc.so.6
#1  0x08048418 in main () at test.c:10
(gdb) 

        定位到了代码的第10行, fwrite产生了core, 在追根溯源, 发现fp为NULL, 于是一切得到了合理解释。


        最后再次说明一下, 在实际开发中, 一定要对fopen的返回值进行校验, 我至少碰到过一次了。项目复杂后, 这种问题搞得人满头大汗。 如果是概率性问题, 那就头要大了。 偶尔, 我在博客中, 为了图简便, 省略了一些检验, 呵呵。







本文转载:CSDN博客