c - 为什么将节点放入此队列的顶部会出现段错误?

标签 c pointers segmentation-fault queue

我的程序有这些结构:

typedef struct Entry { // node
  void *data; // whatever our data is, goes here
  struct Entry *next; // next node
} Entry;

typedef struct {
   int (*compare)(const void*a, const void *b); // compare func
   Entry *top; // head
   Entry *bottom; // tail
} *Queue;

并使用它们创建一个队列:

Queue create( int (*cmp)(const void*a, const void*b) ) {

   Queue Q = NULL;
   Q = (Queue)malloc(sizeof(Queue));

   Q->top = NULL;
   Q->bottom = NULL;

   Q->top = malloc(sizeof(Entry));
   Q->bottom = malloc(sizeof(Entry));

   Q->compare = cmp;

   return Q;
}

使用此插入:

void insert( Queue queue, void *data ) {
   // start at the top
   Entry *slot = queue->top;
   Entry *newNode = malloc(sizeof(Entry));
   newNode->data = data;
   newNode->next = NULL;

   // is it an entirely empty queue?
if (que_empty(queue)) {
      // put our data into the dummy slot
      queue->top = newNode;
   }
}

从给定的正确且无法修改的主测试程序文件运行(要插入的数据位于全局变量中):

int main( void ) {
        Queue up, down, fifo;

        up = create( cmp_int64_ascend );
        if( up == NULL ) {
                fputs( "Cannot create ascending queue\n", stderr );
                exit( EXIT_FAILURE );
        }

        down = create( cmp_int64_descend );
        if( down == NULL ) {
                fputs( "Cannot create descending queue\n", stderr );
                exit( EXIT_FAILURE );
        }

        fifo = create( NULL );
        if( fifo == NULL ) {
                fputs( "Cannot create FIFO queue\n", stderr );
                exit( EXIT_FAILURE );
        }

        puts( "Testing the ascending queue" );
        process( up );

        puts( "\nTesting the descending queue" );
        process( down );

        puts( "\nTesting the FIFO queue" );
        process( fifo );

        destroy( up );
        destroy( down );
        destroy( fifo );

        return( 0 );
}

当我尝试运行它时,它开始无休止地重复看起来像指针地址的内容(例如,18087952)并崩溃。我正在努力解决的问题是queue->top = newNode。

如何将 newNode 分配到队列顶部?

最佳答案

Queue Q = NULL;
Q = (Queue)malloc(sizeof(Queue));

Queue 在这里是一个指针类型,因此您分配的是指针的大小而不是结构的大小。

您可能不应该给指针类型起一个像 Queue 这样的名称,因为它没有表明它是一个指针 - 这只会令人困惑并导致像上面那样的错误。

最好将结构本身命名为 Queue,并在需要指针的地方使用 Queue*

关于c - 为什么将节点放入此队列的顶部会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26660497/

相关文章:

c - 在给定字段偏移量的情况下确定结构的字段

c - 错误: Expected primary-expression before '=='

C的怪异指针运算2

c - 简单链表段错误

c++ - 用于模拟 Spring 运动的代码中的段错误

c++ - 使用 sizeof 而不是文字

c - 从 C 文本文件中提取随机单词时出现段错误

c - 在C中存储指针

delphi - 存储 Delphi 接口(interface)引用时出现奇怪的 AV

c - Cache Sim C 程序中的 SegFault