[英]C linked list: head is changing
我使用結構作為鏈表,但是由於最近的更改(我忘了檢查git repo,所以我不記得哪個更改)head元素中的一個struct變量正在改變。 在執行下面顯示的代碼時,post-> filename得到了一個有效的字符串,但是在離開方法之后,head_post-> filename( 應該指向完全相同的值)有一些添加的垃圾。 字符串“20130804-0638.md”變為“20130804-0638.md :\\ 020”。
我想念的任何想法?
結構:
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;
}
}
我認為在為filename
分配內存時也需要計算'\\0'
,因為strlen()
不計算它。
...
// ------------- +1 for '\0'
post->filename = malloc(sizeof(char) * (strlen(ep->d_name) +1 ));
strcpy(post->filename, ep->d_name);
post->next = NULL;
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.