簡體   English   中英

“程序收到信號 SIGSEGV,分段錯誤。” 來自 gdb 調試器的錯誤消息

[英]“Program received signal SIGSEGV, Segmentation fault.” error message from gdb debugger

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

問題是 function

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

處理 main 中定義的原始指針的副本,因為指針是按值傳遞的。

您應該像這樣聲明 function

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

並稱它為

push( &list_head, 1, 4.0 );

下面是如何定義 function 的示例(我假設 function 將節點附加到其尾部)。

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;
}   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM