braindump
braindump

Reputation: 309

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

Upvotes: 0

Views: 115

Answers (1)

Rohan
Rohan

Reputation: 53326

I think you need to count for '\0' as well while allocating memory for filename, as strlen() does not count for it.

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

Upvotes: 2

Related Questions