Я выполняю какое-то упражнение со связанными списками на C. И столкнулся с проблемой указателя. Я пытаюсь реализовать функцию RemoveListByIndex (list, index). И пока я этот код. ФункцияОсвобождение узла в связанном списке
void RemoveNodeByIndex(struct node** head,int index) // NOT WORKING YET
{
// Remove node list
struct node* current = GetNodeByIndex(*(&head), index);
struct node* prev = GetNodeByIndex(*(&head), index-1);
// For debugging
PrintHRLine();
printf("Deleting item %d from list.\n", index);
printf("Item %d data = %d\n", index, current->data);
PrintHRLine();
// Change link from prev link node to the next
prev->link = current->link;
// Unlink node wished to delete
current->link = NULL;
current->data = 0;
// Free data
free((struct node*) current);
}
GetNodeByIndex:
struct node* GetNodeByIndex(struct node** list, int index)
{
// Return node by an index given
// if error it returns NULL
// for i < index
// next_node <- node.link
// node <- next.node
// return next_node
struct node* current = *list;
int counter = 0;
if (current)
{
while (current->link != NULL)
{
if (counter == index)
return current;
current = current->link;
counter++;
}
}
else
{
return NULL;
}
return NULL;
}
мой список структурирована следующим образом:
struct node
{
int data;
struct node* link;
};
И я вызываю функцию из моего основного кода, как это:
int main()
{
struct node* head = NULL;
struct node* edit_node = NULL;
int i;
edit_node = (struct node*)malloc(sizeof(struct node));
// Create a list of 10 elements
for (i = 0; i < SIZE_OF_LIST; i++)
{
struct node* item = (struct node*) malloc(sizeof(struct node));
item->data = i;
if (i==0)
head = item;
printf("(item+%d)->data = %d\n",i,i);
if (i<SIZE_OF_LIST-1)
{
item->link = (item+i+1);
printf("(item+%d->link = (item+%d+1);\n", i, i);
printf("(item+%d adress = 0x%lx\n",i, (unsigned long int) &item+i);
}
else
{
item->link = NULL;
printf("(item+%d->link = NULL;\n", i);
}
}
// RemoveNodeByIndex(head, 5);
// PrintListData(&head);
edit_node->data = 1001;
AddLastNode(&head, &edit_node);
SearchNode(&head, 101);
RemoveNodeByIndex(&head, 8);
PrintListData(&head);
// Free memory
free(item);
free(edit_node);
free(head);
return 0;
}
Кажется, все кажется f ine, за исключением того, что когда я получаю вызов free(). он не работает. выхода:
===================================
Deleting item 8 from list. Located : 0x7fffd20ecad0
Item 8 data = 6
===================================
*** Error in `./a.out': double free or corruption (out): 0x00000000011b2090 ***
Aborted (core dumped)
У меня есть подозрение, что я обработка моего указателя какие-то образом неправильно. Но что я делаю неправильно?
EDIT: Я включил весь мой исходный код в следующей ссылке: SOURCE CODE И я включил весь вывод, сгенерированный программой здесь: OUTPUT
Спасибо, на заранее.
Попробуйте отладить. Или используйте Valgrind .... –
почему 'free ((struct node *) current);' требуется литье? –
Если вы используете связанный список, сделайте это 'current = (* (head) + index);' не находится в поиске n-го узла. – Rohan