访问冲突读取位置(C中的链接列表)

时间:2015-01-18 20:08:08

标签: c

我收到错误"访问违规读取位置0xFEEEFEF2。"在Microsoft Visual Studio中的while (tmp->next)行。我不知道如何解决这个问题。 我已经阅读了类似的帖子,但他们并没有解决我的问题。我很感激任何帮助。提前谢谢。

#include <stdio.h>
#include <string.h>

typedef struct element {
    char ch;
    struct element *next;
} element;

void WriteAll(element *head)
{
    element *temp = head;
    printf("Lista:\n");
    while (temp)
    {
        printf("%c\n", temp->ch);
        temp = temp->next;
    }
    printf("\n");
}

int AddToBeginning(element **head, char value)
{
    element *n;
    if (!(n = (element*)malloc(sizeof(element)))) return 0;
    n->next = *head;
    n->ch = value;
    *head = n;
    return 1;
}

int DeleteChar(element **head, char value)
{
    element *tmp, *usun;
    if (!(*head)) return 0;
    while (*head && (*head)->ch==value)
    {
        usun = *head;
        *head = (*head)->next;
        free(usun);
    }
    if (!(*head)) return 1;
    tmp = *head;
    while (tmp->next)
    {
        if (tmp->next->ch == value)
        {
            element *k = tmp;
            tmp->next = tmp->next->next;
            free(k);
        }
        else {
        tmp = tmp->next;
        }
    }
    return 1;

}

int main()
{
    element *head = NULL;
    if (!AddToBeginning(&head, 'B')) printf("Error - AddToBeginning");
    if (!AddToBeginning(&head, 'A')) printf("Error - AddToBeginning");
    if (!AddToBeginning(&head, 'A')) printf("Error - AddToBeginning");
    if (!AddToBeginning(&head, 'B')) printf("Error - AddToBeginning");
    if (!AddToBeginning(&head, 'F')) printf("Error - AddToBeginning");
    if (!AddToBeginning(&head, 'A')) printf("Error - AddToBeginning");

    if (!DeleteChar(&head, 'A')) printf("Error - DeleteChar");
    WriteAll(head);
}

1 个答案:

答案 0 :(得分:3)

您尝试在此处访问free d tmp

if (tmp->next->ch == value)
{
    element *k = tmp; // <------------+
    tmp->next = tmp->next->next; //   |
    free(k); // free tmp -------------+
}
tmp = tmp->next;
/*     ^ tmp was freed */