繁体   English   中英

在链接列表 C 中递归追加和新节点创建的一致分段错误

[英]Consistent segmentation fault on recursive appending and new node creation in a Linked List C

我有一个带有 2 个字段( intchar* )的结构,我应该创建一个包含这种类型节点的列表,问题是递归算法似乎是正确的,但是每次编译它都会给我一个SIGSEGV错误,因为分配 new_node->data ->number = stud->number,更具体地说,结果 data = {struct fields* | 0x0} NULL 和下一个 = {结构节点* | 0x0} NULL。 有什么帮助吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct fields{
    int number;
    char *name;
};

struct Node {
    struct fields *data;
    struct Node* next;
};

struct Node *newNode(struct fields* data);
struct Node* insertEnd(struct Node* head, struct fields* data);
struct Node* insertEnd(struct Node* head, struct fields* data);
void traverse(struct Node* head);
void init_fields (struct fields* stud);

// Allocates a new node with given data
struct Node *newNode(struct fields* data) {
    struct Node *new_node = malloc (1000*sizeof(*new_node));
    new_node->data->number = data->number;
    new_node->data->name = data->name;
    new_node->next = NULL;
    return new_node;
}

struct Node* insertEnd(struct Node* head, struct fields* data){

    if (head == NULL)
        return newNode(data);

    else
        head->next = insertEnd(head->next, data);
    return head;
}

void traverse(struct Node* head){
    if (head == NULL)
        return;

    printf("\n%d %s\n", head->data->number, head->data->name);
    traverse(head->next);
}

int main(){
    struct Node* head = NULL;
    struct fields* stud = malloc(1000* sizeof(*stud));
    init_fields (stud);
    if (stud == NULL){
        exit(EXIT_FAILURE);
    }

    printf("\nInsert number: ");
    scanf("%d", &stud->number);
    fflush(stdin);
    printf("\nInsert name: \n");
    scanf(" %[^\n]s", stud->name);
    head = insertEnd(head, stud);
    printf("\nInsert number: ");
    scanf("%d", &stud->number);
    fflush(stdin);
    printf("\nInsert name: \n");
    scanf(" %[^\n]s", stud->name);
    head = insertEnd(head, stud);
    traverse(head);
}
void init_fields (struct fields* stud){
    stud->number = 0;
    stud->name = malloc(50*sizeof(char));
}

您需要分配data

struct Node *newNode(struct fields* data) {
    struct Node *new_node = malloc (1000*sizeof(*new_node));
    new_node->data = malloc(sizeof(*new_node->data));
    new_node->data->number = data->number;
    new_node->data->name = data->name;
    new_node->next = NULL;
    return new_node;
}

将来,您可以找到使用gdblldb的确切问题所在。 它会为您指出确切的路线,从那里问题就很明显了。

这里:

struct Node *new_node = malloc (1000*sizeof(*new_node));

您只为 new_node 分配 memory。 这个领域呢?

struct fields *data;

它必须以某种方式初始化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM