两次使用malloc后,“堆已损坏”

时间:2018-08-15 08:53:01

标签: c visual-studio malloc heap-memory

我有一个要构建的“单词”的链接列表,我做了一个名为“ 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;

        }


    }
}

2 个答案:

答案 0 :(得分:0)

这里

        while (temp->next_line != NULL)
        {
            temp = temp->next_line;
            temp->next_line = next; // move out of the loop
        }

您可能希望将最后一个作业移出循环。

答案 1 :(得分:0)

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

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

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

不执行任何操作,因为'machine_code-> next'值为null。因此不会执行循环内的代码。并且我们没有在这里获得链接列表,但是零星的节点之间没有相互连接。 您可能希望(如此处其他文章所指出的那样)具有以下内容:

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