I want to delete node from singly linked list using only one local pointer variable in C, the debugger stops on the free(cur)
of the delete
function without any error, but it runs normally in free(cur->next)
, why is this? What error in this code section?
struct node
{
int val;
struct node *next;
};
typedef struct
{
struct node *header;
} List;
void add(List *pList, int val)
{
struct node *new_node = malloc(sizeof pList->header);
if (new_node == NULL)
{
exit(EXIT_FAILURE);
}
new_node->val = val;
new_node->next = pList->header;
pList->header = new_node;
}
void delete(List *pList, int val)
{
struct node *cur = pList->header;
if (cur != NULL)
{
if (cur->val == val)
{
struct node *temp = cur->next;
//debug stop in free(cur) without any error,why?
free(cur);
cur = temp;
}
else
{
while (cur->next != NULL && cur->next->val != val)
{
cur = cur->next;
}
if (cur->next != NULL)
{
struct node *temp = cur->next->next;
// run normally, why?
free(cur->next);
cur->next = temp;
}
}
}
}