gpt4 book ai didi

c - "Segmentation fault (core dumped)"从文本文件中读取单词并将其添加到列表时出错

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:35 25 4
gpt4 key购买 nike

我有这段代码试图从存储在 .txt 文件中的单词列表中读取单词

char *getWord(char *filename)  {
char formatstr[15], *word;
static FILE *input;
static int firstTime = 1;
if (firstTime) {
input = fopen(filename, "r");
if (input == NULL) {
printf("ERROR: Could not open file \"%s\"\n", filename);
exit(1);
}
firstTime = 0;
}
word = (char*)malloc(sizeof(char)*WORDLEN);
if (word == NULL) {
printf("ERROR: Memory allocation error in getWord\n");
exit(1);
}
sprintf(formatstr, "%%%ds", WORDLEN-1);
fscanf(input, formatstr, word);
if (feof(input)) {
fclose(input);
return NULL;
}
return word;
}

然后这段代码尝试将其存储到链表中

struct num1* wdStr(int wdLength, char *filename)
{

int d; // total words.
char *wordC;

struct num1 *head = NULL;
struct num1 *temp;

d = edCount(filename);

for(int i = 0; i < d; i++)
{
wordC = getWord(filename);

if(strlen(wordC) == wdLength)
{
temp = (struct num1*)malloc(sizeof(struct num1));
temp->val = wordC;
temp->next = head;
head = temp;
}
}
//return head;
}

edCount 只是计算有多少个单词。

所以在运行程序之后,总是在最后一个词之前我得到一个“段错误(核心转储)”错误。我知道我在使用指针时做错了什么,但我仍然找不到什么。

最佳答案

after running the program, always before the last word, I get a "Segmentation fault (core dumped)"

这是因为您的 getWord返回 NULL最后一句话之后,但是你的main电话 strlen无条件地在上面。这取消引用了 NULL指针,导致崩溃。

请注意,您的代码会产生内存泄漏:您的 getWord实现忘记了 free分配的word返回前NULL用于流标记的结束。

注意:除非这是关于静力学的特定学习练习,否则使用 FILE *input非常值得怀疑,因为它使您的 getWord无正当理由不可重入。

关于c - "Segmentation fault (core dumped)"从文本文件中读取单词并将其添加到列表时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20265901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com