This is code to put directory entry strings (from the root directory, in this case) into a single-linked list. I do not understand why a seg fault occurs at the line commented as such. I must be doing the string copying wrong?
I can only think that space for the string to go has not been reserved, but I thought I'd already reserved it by tmp1 = (struct node *)malloc(sizeof(struct node));
?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
struct node {
struct dirent *ent;
struct node *right;
};
void appendnode(struct node **, struct dirent **);
int main() {
DIR *d;
struct dirent *d_ent;
struct node *list;
list = NULL;
d = opendir("C:/");
d_ent = readdir(d);
while (d_ent) {
appendnode(&list, &d_ent);
d_ent = readdir(d);
}
getchar();
return 0;
}
void appendnode(struct node **q, struct dirent **r) {
struct node *tmp1, *tmp2;
tmp1 = (struct node *)malloc(sizeof(struct node));
strcpy(tmp1 -> ent -> d_name, (*r) -> d_name); // <-- Causes seg fault. Why?
tmp1 -> right = NULL;
if (!*q) {
*q = tmp1;
} else {
tmp2 = *q;
while (tmp2 -> right) {
tmp2 = tmp2 -> right;
}
tmp2 -> right = tmp1;
}
}