我正在使用一个我命名为 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'
也没有空间,当您将它们传递给 strlen
、strcpy
或 print它们与 %s
导致未定义的行为。
您需要分配更多内存。
注意 - 您在每次迭代中分配内存,但永远不会释放
其中任何一个。这会导致内存泄漏。
I am not sure why
curr = head
does not modify the head when I modifycurr
那是因为 curr
指向 head
。如果您执行 curr=we
,curr 将停止指向 head
并指向 we
。这不会改变 head
。
关于C Segmentation Fault(核心转储)与链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34261791/