2017-03-16 28 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);