在LinkedList C中使用free()和内存分配

时间:2017-03-16 19:24:24

标签: c linked-list dynamic-memory-allocation

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

typedef struct NodeClass {

    char lineThatContainsWord[100];
    int lineNumber;
    struct NodeClass *next;

} Node;

int main(void) {
    Node *head;
    head = malloc(sizeof(Node));
    Node *tail = NULL;

    head->next = tail; /* sets head equal to NULL */
    strcpy(head->lineThatContainsWord,"hello");
    head->lineNumber = 5;
    free(head);

    head->next = malloc(sizeof(Node));
    head->next->next = NULL;
    strcpy(head->next->lineThatContainsWord,"hello2");
    head->next->lineNumber = 10;

    tail = head->next;
    free(tail);
    printf(tail->lineThatContainsWord);
    printf("\nlineNumber is %d",tail->lineNumber);

    return 0;
}

我假设通过设置tail = head-&gt;接下来,它将打印head-&gt; next节点的值。但是,这个印刷

hello2
lineNumber is 0

为什么只有lineThatContainsWord更新?为什么lineNumber不是?

2 个答案:

答案 0 :(得分:1)

您导致未定义的行为,因为您在释放内存后访问headtail指向的内存(当我尝试您的程序时,我遇到了分段违规错误,但是您不能依靠这个)。摆脱free(head);free(tail);行,程序将打印出来:

hello2
lineNumber is 10

如你所料。

答案 1 :(得分:0)

当您删除要输出的数据成员的节点时,您希望程序输出什么?

我认为你的意思是以下

Node *head = malloc(sizeof(Node));

head->next = NULL; /* sets next equal to NULL */
strcpy(head->lineThatContainsWord,"hello");
head->lineNumber = 5;

Node *tail = head;

tail->next = malloc(sizeof(Node));
tail->next->next = NULL;
strcpy(tail->next->lineThatContainsWord,"hello2");
tail->next->lineNumber = 10;

tail = tail->next;

printf(tail->lineThatContainsWord);
printf("\nlineNumber is %d",tail->lineNumber);

free( tail );
free( head );