有趣的问题之野指针

博主在编写解析JSON字符串的C++程序时遇到了段错误,通过GDB调试定位到问题出在野指针上。在第48行发现一个指针变量未分配内存。修复这个问题后,程序成功运行,输出了预期结果。博客记录了解决此类问题的经验,以备后用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在写解析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$ 

问题解决。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值