Thursday, 5 September 2013

C linked list: head is changing

C linked list: head is changing

I'm using a struct as a linked list but since a recent change (I forgot to
check into the git repo, so I don't remember which change) one of my
struct variables in the head element is changing. While executing the code
shown below, post->filename got a valid string, but after leaving the
method, head_post->filename (which should point to the exact same value)
has some added garbage. The string "20130804-0638.md" becomes
"20130804-0638.md�:\020".
Any Idea what I miss?
Struct:
struct posting {
char *filename;
char timestamp[17];
char *url;
char *title;
char *html;
struct posting *next;
};
struct posting *head_post = NULL;
Code:
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;
}
}

No comments:

Post a Comment