双重免费或腐败(外出)c

时间:2018-06-05 12:36:28

标签: c linked-list runtime-error free

我正在编写一个简单的linked_list程序来删除节点。 但我收到运行时错误:

  

双重免费或腐败(外出)

。 如果我注释掉free(t1),那么错误就消失了。 请解释我的错误。 谢谢。

#include <stdio.h>
#include <stdlib.h>

struct node
{
  int data;
  struct node* link;
};

int main()
{
    struct node a,b,c,d;
    struct node* head = &a;

    a.data=1;
    b.data=2;
    c.data=3;
    d.data=4;


    head->link = &b;
    head->link->link = &c;
    head->link->link->link = &d;
    d.link = NULL;

    struct node* new = (struct node*)malloc(sizeof(struct node));   //new node creation
    new->data=5;

    struct node*t;
    t=head;

//deleting node with data=3

    while(t->link->data!=3)
        t=t->link;

    struct node* t1 = t->link;  //storing address of node to be deleted in t1 
    t->link = t1->link;         //breaking connection with node to be deleted

    free(t1);      //freeing the memory used by deleted node

    while(head)                         //Traversing...
    {
        printf("%d->",head->data);
        head = head->link;
    }
    printf("NULL"); 

return 0;       
}

0 个答案:

没有答案