gpt4 book ai didi

c - 使用malloc两次后为"A heap has been corrupted"

转载 作者:行者123 更新时间:2023-11-30 16:29:26 31 4
gpt4 key购买 nike

我有一个正在尝试构建的“单词”链接列表,我创建了一个名为“add_to_mem”的函数,它将下一个单词添加到链接列表中。我对代码进行了几次检查,发现他工作了两次 - 一次当链接列表为 NULL 时,一次当它不是 NULL 时 - 它确实工作,但在我第三次调用时该方法 - 我收到“堆已损坏”错误。代码:

    typedef struct { unsigned int val : 14; } word;

typedef struct machine_m

{

word * current;
int line_in_memo;
char * sign_name;

struct machine_m * next_line;
}Machine_Memo;

功能:

    /*Adding a word to the memory.*/
void add_to_mem(word * wrd, int line, char * sign_name)
{
Machine_Memo * temp = NULL, *next = NULL;
if (machine_code == NULL)
{

machine_code = (Machine_Memo *)malloc(sizeof(Machine_Memo));
if (machine_code == NULL)
{
printf("Memory allocation has failed.");
exit(1);
}
machine_code->current = wrd;
machine_code->line_in_memo = line;
machine_code->sign_name = sign_name;
machine_code->next_line = NULL;

}
else
{
printf("token has been reached");
temp = machine_code;
next = (Machine_Memo *)malloc(sizeof(Machine_Memo)); //Line of error
if (next == NULL)
{
printf("MEMORY ALLOCATION HAS FAILED. EXITING PROGRAM.\nThe problem has occured on code line %d", 775);
exit(0);
}
next->current = wrd;
next->line_in_memo = line;
next->sign_name = sign_name;
next->next_line = NULL;

while (temp->next_line != NULL)
{
temp = temp->next_line;
temp->next_line = next;

}


}
}

最佳答案

据我了解代码,它不会创建链表。它创建节点,但不将它们链接在一起。

第一次调用时,会创建 machine_code(列表头)。在下一次调用时,将创建节点“next”,但是循环:

while (temp->next_line != NULL)
{
temp = temp->next_line;
temp->next_line = next;
}

不执行任何操作,因为“machine_code->next”值为空。所以循环内的代码不会被执行。我们在这里得到的不是一个链接列表,而是零星的节点,这些节点没有相互连接。你可能想要(正如这里另一篇文章所指出的那样)有类似的东西:

while (temp->next_line != NULL)
{
temp = temp->next_line;
}
temp->next_line = next;

关于c - 使用malloc两次后为"A heap has been corrupted",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51855691/

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