gpt4 book ai didi

c - 访问违规读取位置(C中的链表)

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:35 24 4
gpt4 key购买 nike

我收到错误“访问冲突读取位置 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);
}

最佳答案

您尝试在此处访问免费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 */

关于c - 访问违规读取位置(C中的链表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28014289/

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