2017-03-16 83 views
-2
#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-> next,它会打印head-> next节点的值。但是,此印刷在LinkedList中使用free()和内存分配C

hello2 
lineNumber is 0 

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

回答

1

您正在导致未定义的行为,因为您在释放内存(当我尝试您的程序时出现了分段违例错误,但您不能依赖于此内存)后访问headtail指向的内存。摆脱free(head);free(tail);线,并计划将打印:

hello2 
lineNumber is 10 

如您所愿。

+0

我的任务要求我释放的变量,所以我释放他们后,我印制和它的工作。但是,我读到释放变量只是释放它们指向的数据。如果我在访问数据后发布数据,完全释放的意义是什么? – csDS

+0

完成使用后可以释放它,以便内存可以用于其他内容。 – Barmar

+0

程序员永远不会释放他们的结构对于程序员来说是不切实际的吗?这会使他们的内存分配效率低下,对吗? – csDS

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