c - 段错误释放内存 - 仅当分配的内存太多时

标签 c pointers segmentation-fault free singly-linked-list

我正在尝试将文件中的单词(每行仅一个单词格式化)读取到单链表中。下面的代码适用于小文件。一旦我开始向要读取的文件添加很多行,我就会开始出现段错误。

产生段错误的行是:来自 destroy() 函数的 free(a->word) 。再次,我想指出两件事:

1) 如果我不调用 destroy() 函数,无论文件有多大,代码都可以正常工作;

2) 如果我调用 destroy() 函数并且单词文件很小(少于 100k 行),代码也可以正常工作。

我不知道是什么原因导致了这种行为。有任何想法吗?谢谢!

 typedef struct dictionary_entry
{
    char *word;
    struct dictionary_entry *next;
}
dictionary_entry;

dictionary_entry *head;
int LENGTH = 50;

int destroy(dictionary_entry *a)
{
    if (a == NULL)
    {
        free(a);
    }

    else
    {
        destroy(a->next);
        free(a->word);
        free(a);
    }

    return 0;
}

void push(char *a)
{
    dictionary_entry *new_data = malloc(sizeof(dictionary_entry));
    new_data->word = a;
    new_data->next = head;
    head = new_data;
}

int main(void)
{
    head = NULL;

    char dictionary_word[LENGTH + 2]; //extra chars for the \0 and \n

    char *added_word = NULL;

    FILE *file = fopen("./victor", "r");

    if (file == NULL)
    {
        return 1;
    }

    while (fgets(dictionary_word, LENGTH + 1, file) != NULL)
    {
        added_word = malloc((LENGTH + 2) * sizeof(char));
        strcpy(added_word, dictionary_word);
        push(added_word);
    }

    fclose(file);

    if (destroy(head) == 0)
    {
        return 0;
    }

    else
    {
        return 1;
    }
}    

最佳答案

如果链表太大,堆栈可能会因递归调用而溢出。尝试迭代方法:

int destroy(dictionary_entry *a)
{
    while(a)
    {
        dictionary_entry *next = a->next;

        free(a->word);
        free(a);

        a = next;
    }

    return 0;
}

关于c - 段错误释放内存 - 仅当分配的内存太多时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49718787/

相关文章:

c - 使用 write()、read() 和 fifo 在 C 中的进程之间共享数据

c++ - 使用 GtkBuilder 但在 GTKmm 上的自动连接信号

C 实现二叉搜索树

pointers - 解释指向Javascript开发人员的指针

Eclipse 段错误 (OSX)

objective-c - 相当于 +[NSString stringWithContentsOfURL :usedEncoding:error:] for CFStringRef

c - 在给定 n 个点的平面中找到正方形

ruby - 这两个方法参数定义有什么区别?

linux - gdb demangler 加载符号时出现段错误

c - strtok() 空字符串输入时出现段错误