【问题标题】:"Program received signal SIGSEGV, Segmentation fault." error message from gdb debugger“程序收到信号 SIGSEGV,分段错误。”来自 gdb 调试器的错误消息
【发布时间】:2020-01-29 21:17:17
【问题描述】:

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

【问题讨论】:

  • 需要将list head的地址传给push()。
  • 欢迎您!请在您的问题中包含推送的定义。正如@VladfromMoscow 所说,您的推送函数声明/定义有问题。
  • 只是指出,push 不一定是自称,因为push 的定义没有提供,只是声明。
  • 我们确实需要push() 的定义来最终回答这个问题。 @CodakBlack,可以将其编辑到您的问题中吗?
  • 如果你已经在调试器中运行你的程序并得到这个错误,你应该看到你得到那个错误的确切位置。在那里,您可以检查变量并检查预期值与实际值。

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


【解决方案1】:

问题在于函数

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    相关资源
    最近更新 更多