我的 C 程序(为背包编写)遇到分段错误。 使用 gdb,
(gdb) ptype $_siginfo
(gdb) ptype $_siginfo._sifields._sigfault
(gdb) p $_siginfo._sifields._sigfault.si_addr
我发现, 当程序尝试引用 0x8 时。 它显示分段错误。 在 gdb 的文档中,他们说 根据目标支持,$_siginfo 也可能是可写的。
有什么想法,我们如何包含上面的内存地址? 这样程序就不会显示分段错误。
此错误也显示在程序中的一个 printf 语句中。 我们可以使用信号 0 来确保程序在该阶段忽略 SIGSEGV 吗?
任何见解都会有帮助
瓦尔格林德: 我尝试使用 valgrind 查看问题: valgrind 的输出如下:
The number of objects is 1200, and the capacity is 38400000.
==2297== Invalid write of size 4
==2297== at 0x400A4E: main (knap1.c:73)
==2297== Address 0x8 is not stack'd, malloc'd or (recently) free'd
==2297==
==2297==
==2297== Process terminating with default action of signal 11 (SIGSEGV)
==2297== Access not within mapped region at address 0x8
==2297== at 0x400A4E: main (knap1.c:73)
==2297== If you believe this happened as a result of a stack
==2297== overflow in your program's main thread (unlikely but
==2297== possible), you can try to increase the size of the
==2297== main thread stack using the --main-stacksize= flag.
==2297== The main thread stack size used in this run was 8388608.
==2297==
==2297== HEAP SUMMARY:
==2297== in use at exit: 14,400 bytes in 3 blocks
==2297== total heap usage: 4 allocs, 1 frees, 14,968 bytes allocated
==2297==
==2297== LEAK SUMMARY:
==2297== definitely lost: 0 bytes in 0 blocks
==2297== indirectly lost: 0 bytes in 0 blocks
==2297== possibly lost: 0 bytes in 0 blocks
==2297== still reachable: 14,400 bytes in 3 blocks
==2297== suppressed: 0 bytes in 0 blocks
==2297== Rerun with --leak-check=full to see details of leaked memory
==2297==
==2297== For counts of detected and suppressed errors, rerun with: -v
==2297== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)
Segmentation fault
增加堆栈大小并没有多大帮助。 知道如何解决这个问题吗?
0x8
的错误地址表示空指针被以小偏移量取消引用。 可能是数组访问,但更可能是位于偏移量 struct
处的 0x8
的字段。
在 gdb 中使用
bt
(回溯)命令来确定错误发生的位置,然后检查是否有直接取消引用的空指针或传递给库函数,然后由库函数取消引用它们。