我有一个我正在尝试构建的"单词"链表,我做了一个名为"add_to_mem"的函数,它将下一个单词添加到链表中。 我对代码进行了几次检查,发现他工作了两次 - 一次是当链表为 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;
这里
while (temp->next_line != NULL)
{
temp = temp->next_line;
temp->next_line = next; // move out of the loop
}
您可能希望将最后一个分配移出循环。