C Segmentation Fault(核心转储)与链表

标签 c struct linked-list malloc

我正在使用一个我命名为 word_entry 的链表。 word_entry 的结构如下:

struct word_entry

{
        char *unique_word ;
        int word_count ;
        struct word_entry *next;
        struct word_entry *prev;
} ;

这就是我使用代码的方式:

struct word_entry *head = NULL;
struct word_entry *curr = NULL;
int read_file( char *file_name )
{
        int initialized = 0;//was head initialized?
        char ch;
        FILE *file;
        struct word_entry *we = malloc(sizeof(struct word_entry));
        we->unique_word = malloc(sizeof(char));
        we->prev = NULL;
        we->next = NULL;
        char *s1 = malloc(sizeof(char));
        char *s2 = s1;
        file = fopen(file_name, "r");//opens the file

        if(!file){
                return 0;//file not opened
        }else{

                while((ch = fgetc(file))!= EOF){
                        if(ch >= 'A' && ch <= 'z'){
                                *s2++ = ch;
                                continue;
                        }
                        if(strlen(s1)>0){
                                if(!initialized){
                                        head = malloc(sizeof(struct word_entry));
                                        curr = head;
                                        initialized = 1;
                                }
                                *s2 = '\0';
                                strcpy(we->unique_word,s1);
                                we->word_count = 1;
                                curr = we;
                                printf("%s\n", head->unique_word);
                                s1 = malloc(sizeof(char));
                                s2 = s1;
                        }
                }
                return 1;
        }
        return 0; //file not opened
}

我不确定为什么我修改curr时curr = head不修改head。我想知道如何实现我的代码,以便每当我修改 curr 时它也会修改 head 中的信息。

最佳答案

您为这些char * 分配内存-

       we->unique_word = malloc(sizeof(char));        // sizeof(char) is 1 
       ....
       char *s1 = malloc(sizeof(char));               

即使您读取一个字符,'\0' 也没有空间,当您将它们传递给 strlenstrcpy 或 print它们与 %s 导致未定义的行为

您需要分配更多内存。

注意 - 您在每次迭代中分配内存,但永远不会释放其中任何一个。这会导致内存泄漏。

I am not sure why curr = head does not modify the head when I modify curr

那是因为 curr 指向 head 。如果您执行 curr=we ,curr 将停止指向 head 并指向 we。这不会改变 head

关于C Segmentation Fault(核心转储)与链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34261791/

相关文章:

可展开二次方程的C程序

java - 如何找到带循环的链表的循环节点?

c - 如何在C中实现内存模拟?

C:信号代码:地址未映射(1)mpirecv

struct - 通过值或指针访问另一个结构

c - 作业 : Freeing data in a struct

c - 将文件中的值读入结构数组时出错

python - 链表在具有动态数组的语言中是否有任何值(value)?

c - 无法使用 Openwrt 工具链 : Undefined reference to _Unwind_Resume and __gcc_personality_v0 构建静态二进制文件

c - 如何使用 lxdialog 创建 GUI(例如 menuconfig)