gpt4 book ai didi

c - 尝试加载链表时 Malloc 崩溃

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

我正在尝试从文本文件初始化链表,这是我的结构:

typedef struct Diagnostic
{
char* disease;
int priority;
}Diagnostic;

typedef struct Fiche Fiche;
struct Fiche
{
char* name;
int age;
Diagnostic diagnostic;

Fiche* next; // because this is a linked list
};

这是我的加载函数:

void loadFiches()
{
int i;
char tmp1[100], tmp2[100];
Fiche* current;
FILE* file = fopen("fiches.txt", "r");

if(file != NULL)
{
while(!feof(file))
{
printf("malloc:");
current = malloc(sizeof(Fiche)); // allocate memory for a new fiche
printf("%p\n", current);

fgets(tmp1, 100, file); // get the name
cleanChar(tmp1); // remove '\n'

fscanf(file, "%d\n", &current->age); // get the age

fgets(tmp2, 100, file); // get the disease
cleanChar(tmp2); // remove '\n'

fscanf(file, "%d\n", &current->diagnostic.priority); // get the priority

current->diagnostic.disease = malloc(strlen(tmp2) * sizeof(char)); // allocate memory for the disease
strcpy(current->diagnostic.disease, tmp2); // copy the disease in the corresponding field

// Then I add this fiche to my linked list
}

}
else printf("error");

fclose(file);
}

这个的输出是

malloc:00350FD8
malloc:00350FF8
malloc:

所以它在第三个 malloc 处崩溃了。请注意,我只初始化疾病字段,因为它是导致崩溃的原因,其他一切正常,因此它不会出现在此代码中。另请注意,在 Debug模式下一切正常。

如果我删除 cleanChar(tmp2);strcpy(current->diagnostic.disease, tmp2);,那么它也能正常工作(但我有一个在第一种情况下不需要\n),这是导致崩溃的两条线的组合。

这是我的 cleanChar 函数:

void cleanChar(char string[100])
{
int i;

for(i = 0; i < strlen(string); i++)
if(string[i] == '\n') string[i] = '\0';
}

有没有人知道可能导致崩溃的原因?我很确定这与我将 fiches 保存到文本文件的方式无关,但这是保存功能:

void saveFiches(List list)
{
int i;
Fiche* current = list.first;
FILE* file;

file = fopen("fiches.txt", "w+");

if(file != NULL)
{
for(i = 0; i < list.size; i++)
{
fprintf(file, "%s\n%d\n%s\n%d\n", current->name, current->age, current->diagnostic.disease, current->diagnostic.priority);
current = current->next;
}
}
else printf("error");

fclose(file);
}

List 是一个包含我的链接列表的第一个元素的结构。

最佳答案

你的字符串 malloc() 差了一个(你不考虑终止 '\0':

current->diagnostic.disease = malloc(strlen(tmp2) * sizeof(char));

应该是:

current->diagnostic.disease = malloc((strlen(tmp2) + 1) * sizeof(char));

并且,由于 sizeof(char) 总是 1 这可能是:

current->diagnostic.disease = malloc(strlen(tmp2) + 1);

除非您想通过取消引用分配给它的指针来确定适当的大小,从而使 malloc() 更健壮:

current->diagnostic.disease = malloc((strlen(tmp2) + 1) *
sizeof(*(current->diagnostic.disease)));

你也可以复制字符串:

current->diagnostic.disease = strdup(tmp2);

无论采用哪种方式,都不要忘记检查结果是否为 NULL

关于c - 尝试加载链表时 Malloc 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48888404/

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