“程序收到信号SIGSEGV,分段故障。”来自gdb调试器的错误消息

时间:2019-09-30 14:43:39

标签: c linked-list singly-linked-list segmentation-fault

while循环中的某些东西给了我这个错误。我不知道要查找什么,因为这个错误似乎很常见,可以用来查找我的特定示例

#include <stdlib.h>
#include <stdio.h>
/*Structure declarations*/
struct Data {
    int id_number;
    float ratings;
};
typedef struct Node{
    struct Data player;
    struct Node *next;
}Node;

/*function declaration*/
void push(struct Node *list_head, int unique_id, float grade);
int main(){
    /* Initialize list_head to Null since list is empty at first */
    Node *list_head = NULL;     
    Node *traversalPtr;

    push(list_head, 1, 4.0);
    push(list_head, 2, 3.87);
    push(list_head, 3, 3.60);

    traversalPtr = list_head;
    while(traversalPtr -> next != NULL){
        printf("%d\n",traversalPtr -> player.id_number);
        traversalPtr = traversalPtr -> next;
    }   
}

...function declarations

1 个答案:

答案 0 :(得分:4)

问题在于该功能

void push(struct Node *list_head, int unique_id, float grade);

使用main中定义的原始指针的副本进行交易,因为指针是通过值传递的。

您应该像这样声明函数

void push(struct Node **list_head, int unique_id, float grade);

并称呼它

push( &list_head, 1, 4.0 );

这里是如何定义函数的示例(我假设函数将节点附加到其尾部)。

int push(struct Node **list_head, int unique_id, float grade)
{
    struct Node *node = malloc( sizeof( struct Node ) );
    int success = node != NULL;

    if ( success )
    {
        node->player.id_number = unique_id;
        node->player.ratings   = grade; 
        node->next = NULL;

        while ( *list_head ) list_head = &( *list_head )->next;

        *list_head = node;
    }

    return success; 
}

也是这个循环

traversalPtr = list_head;
while(traversalPtr -> next != NULL){
    printf("%d\n",traversalPtr -> player.id_number);
    traversalPtr = traversalPtr -> next;
}   

不正确。看起来应该像

traversalPtr = list_head;
while(traversalPtr != NULL){
    printf("%d\n",traversalPtr -> player.id_number);
    traversalPtr = traversalPtr -> next;
}