有趣的问题之野指针

  • Post author:
  • Post category:其他


在写解析json字符串的程序中,出现了段错误。

esdon@ubuntu:/mnt/hgfs/tolinux/net/sql$ gcc toelem.c -o toelem -ljson
esdon@ubuntu:/mnt/hgfs/tolinux/net/sql$ ./toelem
Segmentation fault (core dumped)

借助gdb调试

![野指针问题](pic/野指针问题.PNG)esdon@ubuntu:/mnt/hgfs/tolinux/net/sql$ gdb toelem core
GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04
Copyright (C) 2012 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-linux-gnu".
For bug reporting instructions, please see:
<http://bugs.launchpad.net/gdb-linaro/>...
Reading symbols from /mnt/hgfs/tolinux/net/sql/toelem...done.
[New LWP 2197]

warning: Can't read pathname for load map: Input/output error.
Core was generated by `./toelem'.
Program terminated with signal 11, Segmentation fault.
#0  0x0804883a in toelem (
    p=0x8048a80 "[{'cmd':0,'name':'zhangsan','passwd':'abc123','buf':'N'},{'cmd':1,'name':'lisi','passwd':'def456','buf':'N'}]", n=2, tenxu=0xbfda1c94)
    at toelem.c:38
38		tenxu[i]->cmd = json_object_get_int(ng_cmd[i]);
(gdb) where
#0  0x0804883a in toelem (
    p=0x8048a80 "[{'cmd':0,'name':'zhangsan','passwd':'abc123','buf':'N'},{'cmd':1,'name':'lisi','passwd':'def456','buf':'N'}]", n=2, tenxu=0xbfda1c94)
    at toelem.c:38
#1  0x080488fb in main () at toelem.c:58
(gdb) 

但是没发现38行和58行有问题。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LpyA3BQo-1618240577007)(pic/野指针问题.PNG)]

因为之前遇到野指针的问题,所以稍微留意了以下48行。发现tb元素是定义了指针,但是没有指向。

给指针指定一个内存空间,继续测试。运行结果如下:

esdon@ubuntu:/mnt/hgfs/tolinux/net/sql$ gcc toelem.c -o toelem -ljson
esdon@ubuntu:/mnt/hgfs/tolinux/net/sql$ ./toelem
cmd:0
name:zhangsan
passwd:abc123
buf:N
cmd:1
name:lisi
passwd:def456
buf:N
esdon@ubuntu:/mnt/hgfs/tolinux/net/sql$ 

问题解决。

这问题很常见,周末被折磨了很久。发文记录一下,提醒自己。



版权声明:本文为EastTao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。