【问题标题】:Why is there a Segmentation fault from trying to add to count and printf?为什么尝试添加到 count 和 printf 时会出现分段错误?
【发布时间】:2023-04-02 10:17:01
【问题描述】:
#include <stdio.h>                         /* the "QueueTypes.h" file, */
#include <stdlib.h>                   /* given above on lines 1:15, is */
#include "QueueImplementation.c"   

void main(void){
    Queue *que;
    ItemType *num;
    num = 0;
    InitializeQueue(que);
    int count = 0;
    int check;
    int i;

    if(Empty(que) != 1){
        count = count + 1;
    }
    printf("%d", count); <- segmentation fault

    if(Remove(que, num) != 0){
        count = count + 1; <- segmentation fault
}

这些是程序中不断出现分段错误的部分。我是否非法访问任何东西?

这是 queueimplementation.c。当我删除被指出的行时,程序运行正常并正常返回错误。

/*   ------------< begin file "QueueImplementation.c" >------------   */

   #include <stdio.h>                         /* the "QueueTypes.h" file, */
   #include <stdlib.h>                   /* given above on lines 1:15, is */
   #include "QueueInterface.h"          /* included in "QueueInterface.h" */
                                             /* on line 3 of Program 7.4. */

   void SystemError(char *errorMsg) {fprintf(stderr,errorMsg);}

   void InitializeQueue(Queue *Q)
   {
      Q->Front = NULL;
      Q->Rear  = NULL;
   }

 /* -------------------- */

   int Empty(Queue *Q)
   {
      return (Q->Front == NULL);
   }
 /* -------------------- */

   int Full(Queue *Q)   
   {                     /* we assume an already constructed queue, Q, is */
      return 0;              /* not full, since it could potentially grow */
   }                                             /* as a linked structure */

/* -------------------- */

   int Insert(ItemType R, Queue *Q)
   {   
      QueueNode *Temp;
                                                   /* attempt to allocate */
      Temp = (QueueNode *) malloc(sizeof(QueueNode));       /* a new node */

      if (Temp == NULL) {               /* Temp = NULL signals allocation */
         SystemError("system storage is exhausted");           /* failure */
     return 0;
      } else {
         Temp->Item = R;
         Temp->Link = NULL;
         if ( Q->Rear == NULL ) {
            Q->Front = Temp;
            Q->Rear = Temp;
         } else {
            Q->Rear->Link = Temp;
            Q->Rear = Temp;
         }
      }
      return 1;
   }

/* -------------------- */

   int Remove(Queue *Q, ItemType *F)
   {   
      QueueNode *Temp;

      if (Q->Front == NULL) {
         SystemError("attempt to remove item from empty Queue");
     return 0 ;
      } else {
         *F = Q->Front->Item;
         Temp = Q->Front;
         Q->Front = Temp->Link;
         free(Temp);
         if (Q->Front == NULL) Q->Rear = NULL;
     return 1;
      }
   }

/* -------------------- */

【问题讨论】:

  • 我怀疑是那些行导致了段错误。能否提供QueueImplementation.c的实现?
  • 您的分段错误没有发生在printf() 或增加count 整数时。最可能的问题是你还没有理解QueueImplementation.c 中发生了什么。
  • 我将在其中添加 QueueImplementation.c,但是当我删除这些行时程序运行良好
  • 出现异常的原因是que 指针未初始化。查找“按值传递”以获得解释。
  • 永远不要#include 实现(又名“.c”)文件!

标签: c list queue


【解决方案1】:

当你将指针que传递给InitializeQueue()时,你还没有初始化它。

更好的实现可能是将指向指针que(即Queue**)的指针传递给InitializeQueue()

void InitializeQueue(Queue **Q)
{
   *Q = malloc(sizeof**Q); // set aside memory for your queue
   Q->Front = NULL;
   Q->Rear  = NULL;
}

然后这样称呼它

Queue *que;
InitializeQueue(&que);

如果你不能改变QueueImplementation.c的实现,那么在函数调用之前调用malloc,像这样:

Queue *que = malloc(sizeof*que);
InitializeQueue(que);

或者根本不使用堆分配(我的建议):

Queue que; // note that this is not a pointer
InitializeQueue(&que); // we have to take the address of it

请注意,使用上述选项,que 只能在定义它的函数内合法访问。但是,这不会影响您,因为您在 main 中定义了它,因此它将在您的程序的整个生命周期中存在。

至于malloc 两个选项,请记住在使用完毕后致电free()。

在将num 传递给Remove() 之前,您也未能在任何地方初始化它。你应该以类似的方式修复它。

您可以考虑使用诸如valgrind 之类的调试器。分段错误并不总是发生(如果它们发生的话)在导致它的同一行代码中,并且作为错误检查的一种方式可能是不可靠的。


附:使用if (Empty(que)) 而不是if (Empty(que) != 1) 就足够了,因为表达式在计算为非零整数时为“真”。可以说它更安全,因为所有“真实”值都不必是1。

附言不要#include.c 文件。包含.h 文件并使用您的主程序编译.c 文件。如果你使用gcc,那么

gcc myprogram.c QueueImplementation.c

其他编译器使用相同的语法(可能某处有异常,但我没有遇到过)。

【讨论】:

  • 我认为我无法更改 QueueImplementation.c 中的任何内容,因为它来自教科书问题。
  • @kyletruong 然后在调用该函数之前对其进行初始化。我修改了我的答案以显示您将如何做到这一点。
  • 好吧,虽然我的程序的其余部分有更多错误要修复,但它似乎正在工作。非常感谢!
  • @kyletruong 如果此答案对您有所帮助,请务必通过单击分数下方的复选标记将其标记为正确答案。
【解决方案2】:

在 C 中,当您只声明一个指针 Queue * 时,它不会神奇地指向一个新的“有效”队列实例。实际上,它指向内存中的一个随机位置,该位置很可能不包含任何对您有意义的内容。

为了简化,在你的代码中你正在做:

  • 给我一个指针 que,我不在乎它指向哪里。
  • 把 { NULL, NULL } 放到指针指向的地方。

所以你正在将 { NULL, NULL } 写入系统内存的随机部分。

这不是你的做法。看看 Luddite 提供的例子。

另外,请阅读这篇文章以了解这里发生了什么:

https://www.cs.cf.ac.uk/Dave/C/node10.html

【讨论】:

  • 好的,感谢您的阅读。我需要继续在这方面进行自我教育。
  • @kyle 指针很棘手,真正理解它们需要时间。你走在正确的道路上。
猜你喜欢
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多