free一个无效指针

1. 错误描述:   刚才写了一个删除单链表的结点函数, 参数是 指向链表的指针和链表中指定删除的结点的指针。  当我free这个待删除的结点, 结果报错。  

2. 为什么会报错?

    我查了查MSDN, 看到“Attepmting  to free an invalid pointer (a pointer to a memory block that was not allocated by calloc, malloc, or realloc) may affect subsequent allocation requests and cause errors”。 意思是  只能free掉由calloc,malloc, realloc申请的内存。 而我试图释放定义的结点所占内存。 

3. 错误代码

status

Delete( struct NODE **rootp, struct NODE *node )

{

    PNode p_node = NULL;



    if ( rootp == NULL ){

        printf( "没有可操作的链表\n" );

        return FALSE;

    }



    if ( node == NULL ){

        printf( "没有指定删除的结点\n" );

        return FALSE;

    }



    if ( node == *rootp ){        

        *rootp = node->next;    /* 删除第一个结点 */



    }else{

        for ( p_node = *rootp;

                p_node != NULL  &&  p_node->next != node;

                    p_node = p_node->next );



                    if ( p_node == NULL ){

                        printf( "指定删除的结点不存在\n" );

                        return FALSE;



                    }else{

                        p_node->next = node->next;    /* 删除中间结点或尾结点 */

                    }

                    

    }

    

/*  问题在这里      */

    free( node );

    node = NULL;

    return TRUE;

}



/* main函数 */

void

main ()

{

    PNode list = (PNode) malloc ( sizeof( struct NODE ) );

    PNode p = NULL;

    Node one, two, three, four;

    

    one.data = 1;

    two.data = 2;

    three.data = 3;

    four.data = 4;

    one.next = &two;

    two.next = &three;

    three.next = &four;

    four.next = NULL;





    list->next = &one;

    p = &three;



    if ( Delete( &list, p ) == TRUE ){

        Put( list );

    }else{

        printf( "删除失败\n" );

    }

}

 

你可能感兴趣的:(free)