2013-09-05 32 views
0

我使用一個結構作爲鏈表,但自最近的變化(我忘了檢查到Git回購,所以我不記得其中改變)我的結構之一頭元素中的變量正在改變。 在執行下面顯示的代碼時,post-> filename有一個有效的字符串,但離開方法後,head_post-> filename(應該指向的值完全相同)有一些額外的垃圾。字符串「20130804-0638.md」變爲「20130804-0638.md :\ 020」。C鏈表:頭正在改變

任何想法我想念什麼?

結構:

struct posting { 
    char *filename; 
    char timestamp[17]; 
    char *url; 
    char *title; 
    char *html; 
    struct posting *next; 
}; 
struct posting *head_post = NULL; 

代碼:

struct posting *post; 
... 
while ((ep = readdir(dp))) { 
    if (ep->d_name[0] != '.' && strstr(ep->d_name, ".md") && strlen(ep->d_name) == 16) { 
    if (head_post == NULL) { 
     head_post = malloc(sizeof(struct posting)); 
     post = head_post; 
    } else { 
     post = head_post; 
     while (post->next != NULL) 
     post = post->next; 
     post->next = malloc(sizeof(struct posting)); 
     post = post->next; 
    } 

    post->filename = malloc(sizeof(char) * strlen(ep->d_name)); 
    strcpy(post->filename, ep->d_name); 
    post->next = NULL; 
    } 
} 
+0

如果您從回購下載最後一個版本,您應該能夠對兩個文件進行差異化,這將突出顯示更改。 ......除非你忘記了這麼多的改變。 –

回答

2

我認爲你需要計數'\0'以及而filename分配內存,因爲strlen()它不計數。

... 
//           ------------- +1 for '\0' 
post->filename = malloc(sizeof(char) * (strlen(ep->d_name) +1)); 
strcpy(post->filename, ep->d_name); 
post->next = NULL; 
... 
+0

我大部分時間都是這樣做的,現在我甚至都沒有想過。謝謝! – braindump