3

I'm trying to learn C pointers these days, when I am trying to deal with string and pointers, and link list I am frequently getting segmentation errors. And I wasn't able to fix these issues (I can't find out the exact line where the segmentation fault is happening). My questions are:

  1. What is the tool to find the line with the segmentation fault in my code?

  2. Is there any material (book or tutorial) that you can suggest to me to know about all issues related to the segmentation faults, their reasons and solutions?

gdb output:

/home/sri/Documents/projects/practice/c/strings/a.out...done.
(gdb) run
Starting program: /home/sri/Documents/projects/practice/c/strings/a.out 
Missing separate debuginfo for /lib64/ld-linux-x86-64.so.2
Try: zypper install -C "debuginfo(build-id)=ecb8ef1a6904a2a3ec60a527f415f520c8636158"
Missing separate debuginfo for /lib64/libc.so.6
Try: zypper install -C "debuginfo(build-id)=bd1473e8e6a4c10a14731b5be4b35b4e87db2af7"
this is print1 char *p 

Program received signal SIGSEGV, Segmentation fault.
0x00000000004005dd in do_print2 (p=0x7fffffffdda0) at string_orguments.c:16
16      strcat(p[0],"added");
(gdb) 
4

1 回答 1

3

当操作系统检测到进程违反内存权限时——对有效内存的无效访问会给出:SIGSEGV.

在输出中:

Program received signal SIGSEGV, Segmentation fault.
 0x00000000004005dd in do_print2 (p=0x7fffffffdda0) at string_orguments.c:16
 16     strcat(p[0],"added");

显示strcat(p[0],"added"); 您正在尝试在只读存储器上写入 - 对有效存储器的无效操作。

注意:strcat函数在第一步尝试a从第二个参数字符串文字中"added"的位置写入 char 。因此,您可能会收到信号,因为写入操作无效代替(可能写入只读存储器)。\0p[0]SIGSEGV\0

另请注意:访问无效地址会给出:SIGBUS

阅读:strcat() 实现有效,但最后会导致核心转储以更好地理解。

从算法上查找分段错误是无法解决的问题,您没有任何工具(自动化工具)可用于此目的。但只有这样才能使用gdb类似的工具来错误您的代码。此外,为了避免分段错误,请准确阅读语言原则/规则。您应该清楚为什么会发生分段错误。那么只有通过实践和经验,您才能学习如何编写更少的错误和更可调试的代码。

此外,您应该了解分段错误发生在运行时。可能您的代码对于某些值集运行良好,但对于某些值集则不行。因此在编译时无法检测到分段。

这也说明了为什么它无法解决问题,因为我们无法编写生成随机无限输入的通用算法并测试您的代码是否完美运行!

于 2013-07-18T21:16:29.510 回答