Что не так в структуре связного списка

List* list_lookup(List* list, char* key)
{
    for (; list != NULL; list = list->next) {
        if (strcmp(list->key, key) == 0) {
            return list;
        }
    }
    return NULL; /* Не нашли */
}

Правильно ли он написан? Просто проверил в отладчике, ругается на эту функцию и вызывает segfault

int fill_dictionary(Dictionary* d)
{
    if (d == NULL) {
        return -1;
    }

    FILE* file;
    char name[] = "./source/d.txt";
    if ((file = fopen(name, "r")) == NULL) {
        printf("Не удалось открыть файл\n");
        return -1;
    }

    fseek(file, 0, SEEK_END);
    long pos = ftell(file);
    if (pos > 0) {
        rewind(file);
    } else {
        return -1;
    }

    char* str = calloc(sizeof(char), 100);
    if (str == NULL) {
        return -1;
    }

    d->count = 0;

    for (int i = 0; fgets(str, 100, file); i++) {
        d->count++;

        char* pch = strtok(str, " \n");

        for (int j = 1; j < 4 && pch != NULL; j++) {
            char* word = strdup(pch);
            d->lines[i] = list_addend(d->lines[i], word, j);
            pch = strtok(NULL, " \n");
            printf("%ld %p %s\n",strlen(pch),&word,word);
            //free(word);
        }

        while (pch != NULL) {
            char* word = strdup(pch);
            d->lines[i] = list_addend(d->lines[i], word, 0);
            pch = strtok(NULL, " \n");
            //free(word);
        }
        //free(pch);
    }
    fclose(file);
    free(str);
    return d->count;
}

Ответы (1 шт):

Автор решения: return

Я б написал этот код вот так:

#define DEFINE_LINKED_LIST(listTypeName, nodeTypeName, itemFieldDef) \
    typedef struct nodeTypeName { \
        itemFieldDef; \
        nodeTypeName* next; \
    } nodeTypeName, listTypeName;
#define DEFINE_LL_FIND_FUNC(funcName, listTypeName, nodeTypeName, itemTypeName, predicate) \
    nodeTypeName* funcName(listTypeName* list, itemTypeName item) { \
        // checks \
        \
        for (nodeTypeName* node = list; node; node = node->next) \
            if (predicate) \
                return node; \
        \
        return NULL; // optional \
    }
typedef char* string;

DEFINE_LINKED_LIST(str_linked_list, str_linked_list_node, string value)
// typedef str_linked_list_node {
//     string value;
//     str_linked_list_node* next;
// } str_linked_list_node, str_linked_list;

DEFINE_LL_FIND_FUNC(strllfind, str_linked_list, str_linked_list_node, string, 
    strcmp(node->value, item) == 0)
// str_linked_list_node* strllfind(str_linked_list* list, string item) {
//     // checks
//
//     for (str_linked_list_node* node = list; node; node = node->next)
//         if (strcmp(node->value, item) == 0)
//             return node;
//
//     return NULL; // optional
// }
→ Ссылка