Reputation: 307
I am getting error "Access violation reading location 0xFEEEFEF2." at line while (tmp->next)
in Microsoft Visual Studio. I have no idea how to fix this.
I've read similar posts but they didn't solve my problem. I'd appreciate any help. Thank you in advance.
#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);
}
Upvotes: 0
Views: 49
Reputation: 53016
You try to access the free
d tmp
here
if (tmp->next->ch == value)
{
element *k = tmp; // <------------+
tmp->next = tmp->next->next; // |
free(k); // free tmp -------------+
}
tmp = tmp->next;
/* ^ tmp was freed */
Upvotes: 3