c - 程序中出现段错误,但 GDB 不显示行号

标签 c gdb segmentation-fault

我正在用 C 编写一个 List ADT。我是 C 新手,正在尝试将代码从 Java 翻译成 C。但是,当我测试 List ADT 时,我不断遇到段错误。

当我在GDB中调试程序时,出现以下错误:

Program received signal SIGSEGV, Segmentation fault. 0x0000000000400be8 in getIndex ()

然后,当我输入命令“where”时,我收到以下消息:

#0 0x0000000000400be8 in getIndex ()

#1 0x0000000000400806 in main ()

下面的代码是发生错误的方法 getIndex():

int getIndex(List L) {
   int returnIndex = 0;
   if (offEnd(L)) return -1;
   else {
      NodeRef currIndex = L->curr;
      while (currIndex != L->front) {
         ++returnIndex;
         currIndex = currIndex->prev;
      }
   }
   return returnIndex;
}

作为引用,offEnd() 方法和 NodeRef 的结构是:

int offEnd(List L) {
   if (L == NULL) {
      printf("List Error: Calling offEnd() on NULL List\n");
      exit(1);
   }
   return (L->length == 0);
}
<小时/>
typedef struct Node {
   int data;
   struct Node* next;
   struct Node* prev;
} Node;

typedef Node* NodeRef;

typedef struct ListObj {
   NodeRef front;
   NodeRef back;
   NodeRef curr;
   int length;
} ListObj;

NodeRef newNode(int node_data) {
   NodeRef N = malloc(sizeof(Node));
   N->data = node_data;
   N->next = NULL;
   N->prev = NULL;
   return (N);
}

任何帮助将不胜感激,因为我是 C 语言新手并且正在挣扎。谢谢。

最佳答案

假设您使用 GCC编译器,您应该使用所有警告和调试信息进行编译

 gcc -Wall -g yoursource.c -o yourbinary

当然,请改进代码,直到完全没有警告为止。

也许getIndexNULL 调用争论。您可以添加

#include <assert.h>

接近 yoursource.c 的开头文件和代码:

int getIndex(List L) {
  int returnIndex = 0;
  assert (L != NULL);
  if (offEnd(L)) return -1;
  else {
    NodeRef currIndex = L->curr;
    while (currIndex != L->front) {
       ++returnIndex;
       currIndex = currIndex->prev;
    }
 }
 return returnIndex;
}

了解assertassert(3) .

顺便说一句,我的观点是,指针在 C 中非常重要,因此您总是需要显式地显示它们。所以有一个typedef struct listnode_st ListNode;并声明ListNode* L (或者也许 ListObj* l ,我不知道 List 是什么)而不是 List L 。我也更喜欢大写的宏,所以建议声明 int getindex(ListNode*l)带小写 l并相应地调整该函数的主体。

最后,你的newNode错误的是:malloc可能会失败,你总是应该处理这样的失败。所以开始吧

NodeRef newNode(int node_data) {
  NodeRef N = malloc(sizeof(Node));
  if (N == NULL) { perror("malloc Node"); exit (EXIT_FAILURE); };

谨防memory leaks ;了解更多关于 C dynamic memory allocation , pointer aliasing , undefined behavior , garbage collection ;仔细阅读malloc(3) ;考虑(至少在 Linux 上)使用内存泄漏检测器,如 valgrind .

关于c - 程序中出现段错误,但 GDB 不显示行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21361945/

相关文章:

使用 pthreads 在 C 中并发读取器和互斥写入器

C 奇怪的错误......把我的头发拉出来

c - 以最优方法在链表中找到最小值

c - gdb 调试器最棘手/有用的命令

c++ - GDB 无法显示堆栈并显示 "#1 0x0000000000000000 in ?? ()"

c - 这段C语言代码有什么问题?

c++ - 从 std::vector 中删除时出现段错误

c - 从 C 中的函数返回二维数组

C - 为什么我会遇到段错误?

c++ - 漂亮的 map 打印机抛出类型错误