C带链表的分段故障(堆芯转储)
我正在使用一个我命名为word\u entry的链接列表。word_条目的结构如下所示:C带链表的分段故障(堆芯转储),c,struct,linked-list,malloc,C,Struct,Linked List,Malloc,我正在使用一个我命名为word\u entry的链接列表。word_条目的结构如下所示: struct word_entry { char *unique_word ; int word_count ; struct word_entry *next; struct word_entry *prev; } ; 这就是我使用代码的方式: struct word_entry *head = NULL; struct word_ent
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
}
struct word_entry*head=NULL;
struct word_entry*curr=NULL;
int读取文件(字符*文件名)
{
int initialized=0;//头是否已初始化?
char ch;
文件*文件;
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(文件名,“r”);//打开文件
如果(!文件){
返回0;//文件未打开
}否则{
而((ch=fgetc(文件))!=EOF){
如果(通道>='A'&通道0){
如果(!已初始化){
head=malloc(sizeof(struct word_entry));
curr=头;
初始化=1;
}
*s2='\0';
strcpy(we->unique_-word,s1);
we->word\u count=1;
curr=we;
printf(“%s\n”,head->unique\u word);
s1=malloc(sizeof(char));
s2=s1;
}
}
返回1;
}
返回0;//文件未打开
}
我不确定为什么curr=head在修改curr时不修改head。我想了解如何实现我的代码,以便无论何时修改curr,它都会修改head中的信息。在您的示例中,您使用带有sizeof(char)的malloc来分配char指针(我假设?) 这是不必要的,您不需要分配char*,您需要初始化这个char指针将指向的内存块 这里要做的是将一块内存写入一个字节
strcpy(we->unique_word,s1);
unique_word是一个指针,指向一个分配了1字节大小的内存块-您正在写入超出已分配范围的内容
更正确的方法是:
we->unique_word = (char *)malloc(strlen(s1) + 1); // For the null terminator
if (!we->unique_word) { /* Handle error where memory was not allocated */ }
strcpy(we->unique_word,s1);
将内存分配给这些
char*
-
we->unique_word = malloc(sizeof(char)); // sizeof(char) is 1
....
char *s1 = malloc(sizeof(char));
即使您读取一个字符,也没有空间容纳'\0'
,当您将它们传递到strlen
时,strcpy
或使用%s
打印它们会导致未定义的行为
你需要分配更多的内存
注意-您可以在每次迭代中分配内存,但决不能释放这些内存。这会导致内存泄漏
我不确定在我修改curr
时为什么curr=head
不修改head
这是因为curr
指向head
。如果您执行curr=we
,curr将停止指向head
,并指向we
。这不会改变头部 这(we->unique_word=malloc(sizeof(char));
)令人担忧;只分配了一个字节,字符串不以null结尾。与char*s1=malloc(sizeof(char))类似代码>。当s2
超出分配给s1
的空间末尾时,循环在第二次迭代中开始调用未定义的行为。从那时起,你就处在一个受伤的世界里。谢谢你的帮助。它消除了我的分割错误。@Shontastic先生很高兴它有帮助:)