C链表:头在变化

时间:2013-09-05 12:04:29

标签: c list pointers struct linked-list

我正在使用一个结构作为链接列表但是因为最近的更改(我忘了检查git repo,所以我不记得哪个更改了)我的一个结构变量头元素正在改变。 在执行下面显示的代码时,post-gt; filename得到了一个有效的字符串,但是在离开方法后,head_post-> filename(应该指向完全相同的值)有一些额外的垃圾。字符串“20130804-0638.md”变为“20130804-0638.md :\ 020”。

我想念的任何想法?

STRUCT:

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

1 个答案:

答案 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;
...