简体   繁体   English

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

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

Something in the while loop is giving me this error. while 循环中的某些东西给了我这个错误。 I can't figure out what to look up because this error seems way to common to find out what to do with my specific example我不知道要查找什么,因为这个错误似乎很常见,可以找出如何处理我的具体示例

#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

The problem is that the function问题是 function

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

deals with copies of original pointers defined in main because the pointers are passed by values.处理 main 中定义的原始指针的副本,因为指针是按值传递的。

You should declare the function like您应该像这样声明 function

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

and call it like并称它为

push( &list_head, 1, 4.0 );

Here is an example of how the function can be defined (I assume that the function appends nodes to its tail).下面是如何定义 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; 
}

Also this loop还有这个循环

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

is incorrect.是不正确的。 It should look like它应该看起来像

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