【问题标题】:Segmentation fault w/ pointer to pointer in different struct in C分段错误,带有指向 C 中不同结构中的指针的指针
【发布时间】:2018-10-19 04:42:50
【问题描述】:

我正在尝试创建一个优先队列链表,但一直遇到分段错误。

我的结构定义如下

typedef struct node {
  char *new_element;
  struct node *next;
  int priority;
} Qnode;

typedef struct {
    Qnode *top;
    Qnode *tail;
    int size;
} Priority_queue;

int main() {
    Priority_queue q;
    init(&q);
    enqueue(&q, "hi", 1);
    return 0;
}

void init(Priority_queue *const q) {
    q->top = NULL;
    q->tail = NULL;
    q->size = 0;
    return 0;
}

下面是我的入队方法导致错误的地方

void enqueue(Priority_queue *const q, const char new_element[], int priority) {

    /*......*/

    Qnode *newNode = (Qnode*) malloc(sizeof(Qnode));
    q->tail->next = newNode; /*causes segmentation fault*/
    q->tail = newNode; /*doesn't cause segmentation fault*/


   /*.......*/
}

我猜我没有正确地动态分配内存,但是我的函数的编写方式是从一个结构指向下一个结构,所以有没有办法解决这个问题?

【问题讨论】:

  • 请使用调试器。 q->tail 是什么?添加到队列中的 first 节点会发生什么情况?
  • q->tail->next = newNode;: 这里Priority_queue q;你分配了第一个节点,这里Qnode *newNode = malloc(sizeof(Qnode));你分配了第三个节点。第二次分配的时间和地点?
  • q->tail 被初始化为NULL 并且你想访问q->tail->next.....这就是问题所在!您可以先更改q->tail 的值,然后再查看q->tail->next

标签: c pointers segmentation-fault


【解决方案1】:

在您的代码中,init()q->tail 初始化为 NULL。而你正在尝试做q->tail->next = newNode。在第一个节点的情况下,它基本上意味着NULL->next = newNode。这就是分段错误的原因。

你的enqueue() 应该是这样的:

void enqueue(Priority_queue *const q, const char new_element[], int priority) {

    /*......*/

    Qnode *newNode = (Qnode*) malloc(sizeof(Qnode));
    if (q->tail) {                /*Do this, only When first node is already allocated*/
        q->tail->next = newNode; 
    }
    q->tail = newNode; 

    /*.......*/

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多