首页 > 解决方案 > 链接列表 - 什么会导致使用 malloc 分配的地址实际上从未被分配?

问题描述

我正在创建一个链接列表,并且在梯子下方的某个地方我没有正确分配地址以将它们链接在一起。

没有编译时错误,但是当我尝试打印list.head->next节点时,我的代码中的错误变得明显。打印结果是一个地址00000000

为什么list.head->next没有被分配到?

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


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

struct List 
{
    struct Node* head;
} list;


void insert_node(struct Node *new_node) 
{
    if (list.head == NULL)
    {
        list.head = new_node;
    }

    else 
    {
        struct Node *temp = list.head->next;

        while (temp != NULL)
        {
            temp = temp->next;
        }

        temp = new_node;  
    }
}

struct Node* create_node(int data)
{
    static int node_number = 0;

    struct Node * new_node= malloc(sizeof(struct Node));
    new_node->data = data;
    new_node->next = NULL;

    printf("Node inside function %d - address:  %p\n", node_number++, new_node);

    return new_node;
}


int main()
{
    struct Node *a = create_node(11);
    struct Node *b = create_node(12);

    insert_node(a);
    insert_node(b);

    printf("%p\n", list.head->next);
}

标签: cdata-structuresmemory-managementlinked-listsingly-linked-list

解决方案


在 else 语句中的函数 insert_node 内

else {
        struct Node *temp = list.head->next;

        while (temp != NULL)
        {
            temp = temp->next;
        }

        temp = new_node;  
    }

更改了未连接到列表的局部变量 temp。

你需要写

else {
        struct Node *temp = list.head;

        while (temp->next != NULL)
        {
            temp = temp->next;
        }

        temp->next = new_node;  
    }

请注意,使函数依赖于全局变量是一个坏主意list。在这种情况下,该函数无法处理其他列表。因此,对于每个列表,例如在程序中使用两个列表时,您需要编写一个单独的函数复制代码。

该函数至少可以按如下方式定义,如下所示。

void insert_node( struct List *list, struct Node *new_node ) 
{
    struct Node **current = &list->head;

    while ( *current != NULL ) current = &( *current )->next;

    *current = new_node;
}

struct Node * create_node( int data )
{
    static unsigned int node_number = 0;

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

    if ( new_node != NULL )
    {
        new_node->data = data;
        new_node->next = NULL;

        printf("Node inside function %u - address:  %p\n", node_number++, ( void * )new_node);
    }

    return new_node;
}

推荐阅读